@alexkroman1/aai-cli 0.16.0 → 0.18.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 (439) hide show
  1. package/dist/{_agent-BopNO5Bq.mjs → _agent-BN21AHsJ.mjs} +4 -4
  2. package/dist/_api-client-Uljj0CQi.mjs +312 -0
  3. package/dist/_api-client.d.ts +69 -1
  4. package/dist/{_bundler-DCuNHjDF.mjs → _bundler-DvZDEu2p.mjs} +67 -7
  5. package/dist/_bundler.d.ts +15 -0
  6. package/dist/_cli-common.d.ts +42 -0
  7. package/dist/{client-bundler-DE-AGdm7.mjs → _client-plugins-kR43nZnb.mjs} +30 -132
  8. package/dist/_client-plugins.d.ts +16 -0
  9. package/dist/{_config-mq1I5Cva.mjs → _config-Dlh8PRRp.mjs} +2 -20
  10. package/dist/_config.d.ts +0 -8
  11. package/dist/{_dev-server-B4ZiXbZj.mjs → _dev-server-C_zidzWj.mjs} +17 -12
  12. package/dist/_dev-session-ticket.d.ts +3 -0
  13. package/dist/_dev-tunnel.d.ts +20 -2
  14. package/dist/_dotenv-file.d.ts +6 -0
  15. package/dist/_init.d.ts +2 -11
  16. package/dist/_output.d.ts +47 -20
  17. package/dist/_safe-write.d.ts +38 -0
  18. package/dist/{_server-common-CVXIeWrY.mjs → _server-common-C6j67AcZ.mjs} +37 -2
  19. package/dist/_server-common.d.ts +16 -0
  20. package/dist/{_slug-api-BnmTHtjd.mjs → _slug-api-B9cptz7Q.mjs} +3 -2
  21. package/dist/_start-affinity.d.ts +70 -0
  22. package/dist/_start-log.d.ts +39 -0
  23. package/dist/_start-router.d.ts +85 -0
  24. package/dist/_start-run.d.ts +101 -0
  25. package/dist/_start-worker.d.ts +61 -0
  26. package/dist/_start-workers-BNdOnTal.mjs +529 -0
  27. package/dist/_start-workers.d.ts +262 -0
  28. package/dist/_studio-zympBLlD.mjs +140 -0
  29. package/dist/_studio.d.ts +14 -0
  30. package/dist/_target-bundle.d.ts +4 -0
  31. package/dist/{_templates-BVMVsQh0.mjs → _templates-ChZuhW66.mjs} +110 -8
  32. package/dist/_templates.d.ts +20 -1
  33. package/dist/{_typecheck-gate-CcX2gLJZ.mjs → _typecheck-gate-BNF5cboL.mjs} +2 -2
  34. package/dist/_ui-C0RufoYZ.mjs +147 -0
  35. package/dist/_ui.d.ts +14 -3
  36. package/dist/_utils-ChU85MEg.mjs +486 -0
  37. package/dist/_utils.d.ts +28 -0
  38. package/dist/_vendor-openers.d.ts +87 -0
  39. package/dist/{_vitest-runner-CKI8_K1b.mjs → _vitest-runner-tzyto9IU.mjs} +7 -3
  40. package/dist/_vitest-runner.d.ts +8 -1
  41. package/dist/{build-BnXLgfk-.mjs → build-BHgd-QYb.mjs} +13 -10
  42. package/dist/build.d.ts +21 -0
  43. package/dist/cli-workflow.d.ts +7 -0
  44. package/dist/cli.d.ts +16 -0
  45. package/dist/cli.mjs +243 -70
  46. package/dist/client-bundler-CImhqcp2.mjs +133 -0
  47. package/dist/client-bundler.mjs +1 -1
  48. package/dist/{console-Bp1kSqz_.mjs → console-DwycgRkC.mjs} +4 -5
  49. package/dist/delete-ZcA3J_3o.mjs +75 -0
  50. package/dist/delete.d.ts +10 -1
  51. package/dist/{deploy-eWDoiwvn.mjs → deploy-CkfkiZE3.mjs} +9 -9
  52. package/dist/{dev-CxZsZsOL.mjs → dev-BX9g6qcf.mjs} +81 -18
  53. package/dist/{eval-Dl8o91yC.mjs → eval-CUKvfxRq.mjs} +4 -4
  54. package/dist/{init-CidslZZz.mjs → init-B9Uw76-_.mjs} +62 -32
  55. package/dist/{login-oJdBWu2B.mjs → login-Ct73CqU1.mjs} +30 -6
  56. package/dist/login.d.ts +2 -0
  57. package/dist/{logs-CkmFdSbr.mjs → logs-BBsUy96d.mjs} +59 -14
  58. package/dist/logs.d.ts +4 -1
  59. package/dist/project-config.mjs +1 -1
  60. package/dist/scaffold/CLAUDE.md +72 -55
  61. package/dist/scaffold/agent-guide/AGENT-API.md +46 -33
  62. package/dist/scaffold/agent-guide/HOSTING.md +11 -0
  63. package/dist/scaffold/agent-guide/TESTING-EVALS.md +105 -36
  64. package/dist/scaffold/agent-guide/TOOLS.md +189 -33
  65. package/dist/scaffold/agent-guide/UI.md +111 -39
  66. package/dist/scaffold/agent-guide/WORKFLOWS.md +234 -160
  67. package/dist/scaffold/package.json +4 -4
  68. package/dist/{secret-DPdPEet2.mjs → secret-CKjHRrVX.mjs} +112 -35
  69. package/dist/start.d.ts +14 -14
  70. package/dist/start.mjs +840 -40
  71. package/dist/{studio-COjK25Rl.mjs → studio-U6DvBNAx.mjs} +123 -35
  72. package/dist/studio.d.ts +1 -0
  73. package/dist/templates/applicant-screening-agent/agent.eval.test.ts +23 -52
  74. package/dist/templates/applicant-screening-agent/agent.test.ts +821 -826
  75. package/dist/templates/applicant-screening-agent/agent.ts +1 -6
  76. package/dist/templates/applicant-screening-agent/client.tsx +1 -19
  77. package/dist/templates/applicant-screening-agent/shared.ts +8 -18
  78. package/dist/templates/applicant-screening-agent/tools/candidate_details.ts +24 -27
  79. package/dist/templates/applicant-screening-agent/tools/proceed_to_emails.ts +75 -82
  80. package/dist/templates/applicant-screening-agent/tools/read_email.ts +24 -24
  81. package/dist/templates/applicant-screening-agent/tools/rescore_with_feedback.ts +92 -99
  82. package/dist/templates/applicant-screening-agent/tools/screen_candidates.ts +72 -83
  83. package/dist/templates/applicant-screening-agent/tools/screening_status.ts +21 -29
  84. package/dist/templates/call-audit-workflow/agent.eval.test.ts +14 -19
  85. package/dist/templates/call-audit-workflow/agent.test.ts +275 -169
  86. package/dist/templates/call-audit-workflow/agent.ts +12 -30
  87. package/dist/templates/call-audit-workflow/client.tsx +9 -27
  88. package/dist/templates/call-audit-workflow/guards.test.ts +24 -71
  89. package/dist/templates/call-audit-workflow/workflows/audit.ts +24 -52
  90. package/dist/templates/call-audit-workflow/workflows/ingest.ts +32 -59
  91. package/dist/templates/call-audit-workflow/workflows/media.ts +4 -44
  92. package/dist/templates/call-audit-workflow/workflows/summarize.ts +72 -107
  93. package/dist/templates/code-interpreter-agent/agent.eval.test.ts +3 -2
  94. package/dist/templates/code-interpreter-agent/agent.test.ts +4 -17
  95. package/dist/templates/code-interpreter-agent/agent.ts +1 -1
  96. package/dist/templates/coding-agent/agent.test.ts +17 -12
  97. package/dist/templates/coding-agent/agent.ts +1 -1
  98. package/dist/templates/custom-pipeline-agent/agent.test.ts +6 -14
  99. package/dist/templates/custom-pipeline-agent/agent.ts +1 -1
  100. package/dist/templates/custom-pipeline-agent/modes.test.ts +0 -1
  101. package/dist/templates/custom-pipeline-agent/stages.test.ts +4 -8
  102. package/dist/templates/document-redline-workflow/agent.test.ts +88 -221
  103. package/dist/templates/document-redline-workflow/agent.ts +22 -32
  104. package/dist/templates/document-redline-workflow/client.tsx +46 -88
  105. package/dist/templates/document-redline-workflow/workflows/prompts.ts +0 -3
  106. package/dist/templates/document-redline-workflow/workflows/redline.ts +33 -50
  107. package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +22 -71
  108. package/dist/templates/emergency-dispatch-agent/agent.test.ts +466 -495
  109. package/dist/templates/emergency-dispatch-agent/agent.ts +27 -43
  110. package/dist/templates/emergency-dispatch-agent/client.tsx +85 -119
  111. package/dist/templates/emergency-dispatch-agent/shared.ts +51 -88
  112. package/dist/templates/emergency-dispatch-agent/tools/incident_add_note.ts +11 -17
  113. package/dist/templates/emergency-dispatch-agent/tools/incident_create.ts +21 -30
  114. package/dist/templates/emergency-dispatch-agent/tools/incident_escalate.ts +60 -63
  115. package/dist/templates/emergency-dispatch-agent/tools/incident_get.ts +6 -15
  116. package/dist/templates/emergency-dispatch-agent/tools/incident_triage.ts +40 -53
  117. package/dist/templates/emergency-dispatch-agent/tools/incident_update_status.ts +41 -47
  118. package/dist/templates/emergency-dispatch-agent/tools/ops_dashboard.ts +2 -2
  119. package/dist/templates/emergency-dispatch-agent/tools/ops_protocols.ts +1 -1
  120. package/dist/templates/emergency-dispatch-agent/tools/ops_run_scenario.ts +13 -10
  121. package/dist/templates/emergency-dispatch-agent/tools/resources_dispatch.ts +42 -51
  122. package/dist/templates/emergency-dispatch-agent/tools/resources_update_status.ts +40 -41
  123. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +14 -42
  124. package/dist/templates/entertainment-picks-agent/agent.test.ts +174 -221
  125. package/dist/templates/entertainment-picks-agent/agent.ts +1 -6
  126. package/dist/templates/entertainment-picks-agent/client.tsx +1 -12
  127. package/dist/templates/entertainment-picks-agent/shared.ts +12 -6
  128. package/dist/templates/entertainment-picks-agent/tools/recommend.ts +2 -2
  129. package/dist/templates/entertainment-picks-agent/tools/revisit.ts +1 -0
  130. package/dist/templates/executive-inbox-agent/agent.eval.test.ts +15 -22
  131. package/dist/templates/executive-inbox-agent/agent.test.ts +515 -527
  132. package/dist/templates/executive-inbox-agent/agent.ts +4 -8
  133. package/dist/templates/executive-inbox-agent/calendar.test.ts +23 -22
  134. package/dist/templates/executive-inbox-agent/client.tsx +1 -23
  135. package/dist/templates/executive-inbox-agent/review.ts +125 -113
  136. package/dist/templates/executive-inbox-agent/shared.ts +3 -0
  137. package/dist/templates/executive-inbox-agent/tools/ask_question.ts +6 -6
  138. package/dist/templates/executive-inbox-agent/tools/draft_reply.ts +16 -18
  139. package/dist/templates/executive-inbox-agent/tools/inbox_status.ts +1 -0
  140. package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +20 -20
  141. package/dist/templates/executive-inbox-agent/tools/new_email.ts +17 -21
  142. package/dist/templates/executive-inbox-agent/tools/open_email.ts +72 -74
  143. package/dist/templates/executive-inbox-agent/tools/review_memory.ts +1 -0
  144. package/dist/templates/executive-inbox-agent/tools/send_calendar_invite.ts +19 -20
  145. package/dist/templates/executive-inbox-agent/tools/triage_inbox.ts +53 -50
  146. package/dist/templates/front-desk-agent/agent.eval.test.ts +22 -14
  147. package/dist/templates/front-desk-agent/agent.test.ts +139 -125
  148. package/dist/templates/front-desk-agent/agent.ts +4 -7
  149. package/dist/templates/front-desk-agent/shared.ts +88 -74
  150. package/dist/templates/front-door-agent/agent.eval.test.ts +61 -0
  151. package/dist/templates/front-door-agent/agent.test.ts +393 -0
  152. package/dist/templates/front-door-agent/agent.ts +35 -0
  153. package/dist/templates/front-door-agent/client.tsx +250 -0
  154. package/dist/templates/front-door-agent/routes.ts +91 -0
  155. package/dist/templates/front-door-agent/shared.ts +35 -0
  156. package/dist/templates/front-door-agent/system-prompt.md +12 -0
  157. package/dist/templates/front-door-agent/tools/leave_message.ts +39 -0
  158. package/dist/templates/front-door-agent/tools/link_phone.ts +49 -0
  159. package/dist/templates/front-door-agent/workflows/announce.ts +38 -0
  160. package/dist/templates/front-door-agent/workflows/digest.ts +53 -0
  161. package/dist/templates/front-door-agent/workflows/pair.ts +28 -0
  162. package/dist/templates/home-assistant-agent/agent.eval.test.ts +5 -9
  163. package/dist/templates/home-assistant-agent/agent.test.ts +513 -399
  164. package/dist/templates/home-assistant-agent/agent.ts +8 -5
  165. package/dist/templates/home-assistant-agent/client.tsx +50 -18
  166. package/dist/templates/home-assistant-agent/tools/cancel_reminders.ts +1 -0
  167. package/dist/templates/home-assistant-agent/tools/remind_me.ts +2 -1
  168. package/dist/templates/hotel-reception-agent/agent.eval.test.ts +27 -52
  169. package/dist/templates/hotel-reception-agent/agent.test.ts +980 -964
  170. package/dist/templates/hotel-reception-agent/agent.ts +8 -21
  171. package/dist/templates/hotel-reception-agent/booking.ts +2 -2
  172. package/dist/templates/hotel-reception-agent/client.tsx +5 -20
  173. package/dist/templates/hotel-reception-agent/concierge.ts +2 -0
  174. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +285 -275
  175. package/dist/templates/hotel-reception-agent/desk.ts +45 -12
  176. package/dist/templates/hotel-reception-agent/hotel.ts +6 -6
  177. package/dist/templates/hotel-reception-agent/restaurant.ts +3 -4
  178. package/dist/templates/hotel-reception-agent/session.ts +14 -30
  179. package/dist/templates/hotel-reception-agent/shared.ts +33 -46
  180. package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +14 -15
  181. package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +1 -0
  182. package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +1 -0
  183. package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +2 -2
  184. package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +13 -10
  185. package/dist/templates/hotel-reception-agent/tools/choose_room.ts +1 -1
  186. package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +6 -7
  187. package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +1 -0
  188. package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +5 -4
  189. package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +6 -5
  190. package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +3 -4
  191. package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +4 -4
  192. package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +1 -0
  193. package/dist/templates/hotel-reception-agent/tools/record_card.ts +1 -1
  194. package/dist/templates/hotel-reception-agent/tools/record_followup.ts +1 -0
  195. package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +1 -0
  196. package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +1 -1
  197. package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +1 -0
  198. package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +1 -0
  199. package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +4 -4
  200. package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +1 -0
  201. package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +4 -3
  202. package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +1 -0
  203. package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +1 -0
  204. package/dist/templates/hotel-reception-agent/tools/set_extras.ts +1 -1
  205. package/dist/templates/hotel-reception-agent/tools/set_stay.ts +1 -1
  206. package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +30 -32
  207. package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +22 -25
  208. package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +1 -0
  209. package/dist/templates/hotel-reception-agent/tools/update_card.ts +5 -4
  210. package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +23 -13
  211. package/dist/templates/kitchen-coach-agent/agent.eval.test.ts +38 -0
  212. package/dist/templates/kitchen-coach-agent/agent.test.ts +204 -0
  213. package/dist/templates/kitchen-coach-agent/agent.ts +22 -0
  214. package/dist/templates/kitchen-coach-agent/client.tsx +232 -0
  215. package/dist/templates/kitchen-coach-agent/history.ts +37 -0
  216. package/dist/templates/kitchen-coach-agent/shared.ts +131 -0
  217. package/dist/templates/kitchen-coach-agent/system-prompt.md +17 -0
  218. package/dist/templates/kitchen-coach-agent/tools/get_kitchen.ts +17 -0
  219. package/dist/templates/kitchen-coach-agent/tools/scale_amount.ts +31 -0
  220. package/dist/templates/kitchen-coach-agent/tools/start_timer.ts +24 -0
  221. package/dist/templates/link-digest-workflow/agent.eval.test.ts +16 -40
  222. package/dist/templates/link-digest-workflow/agent.test.ts +84 -164
  223. package/dist/templates/link-digest-workflow/agent.ts +27 -42
  224. package/dist/templates/link-digest-workflow/api-client.ts +3 -2
  225. package/dist/templates/link-digest-workflow/client.tsx +5 -5
  226. package/dist/templates/link-digest-workflow/workflows/digest.ts +53 -95
  227. package/dist/templates/medication-safety-agent/agent.eval.test.ts +10 -30
  228. package/dist/templates/medication-safety-agent/agent.test.ts +16 -46
  229. package/dist/templates/medication-safety-agent/agent.ts +1 -4
  230. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +13 -10
  231. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +238 -396
  232. package/dist/templates/meeting-recap-agent/agent.test.ts +414 -1073
  233. package/dist/templates/meeting-recap-agent/agent.ts +26 -67
  234. package/dist/templates/meeting-recap-agent/system-prompt.md +1 -0
  235. package/dist/templates/meeting-recap-agent/tools/keep_transcript.ts +10 -12
  236. package/dist/templates/meeting-recap-agent/tools/request_recap.ts +9 -20
  237. package/dist/templates/meeting-recap-agent/workflows/recap.ts +224 -547
  238. package/dist/templates/outbound-call-agent/agent.eval.test.ts +10 -12
  239. package/dist/templates/outbound-call-agent/agent.test.ts +419 -453
  240. package/dist/templates/outbound-call-agent/agent.ts +57 -62
  241. package/dist/templates/outbound-call-agent/api.ts +53 -68
  242. package/dist/templates/outbound-call-agent/client.tsx +105 -176
  243. package/dist/templates/outbound-call-agent/shared.ts +10 -39
  244. package/dist/templates/outbound-call-agent/system-prompt.md +3 -4
  245. package/dist/templates/outbound-call-agent/tools/end_call.ts +15 -12
  246. package/dist/templates/outbound-call-agent/tools/press_keys.ts +8 -13
  247. package/dist/templates/outbound-call-agent/workflows/call.ts +94 -63
  248. package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +18 -54
  249. package/dist/templates/pizza-ordering-agent/agent.test.ts +205 -244
  250. package/dist/templates/pizza-ordering-agent/agent.ts +5 -12
  251. package/dist/templates/pizza-ordering-agent/client.tsx +3 -14
  252. package/dist/templates/pizza-ordering-agent/shared.ts +31 -36
  253. package/dist/templates/pizza-ordering-agent/tools/add_pizza.ts +1 -0
  254. package/dist/templates/pizza-ordering-agent/tools/place_order.ts +5 -2
  255. package/dist/templates/pizza-ordering-agent/tools/remove_pizza.ts +1 -0
  256. package/dist/templates/pizza-ordering-agent/tools/update_pizza.ts +2 -3
  257. package/dist/templates/pizza-ordering-agent/tools/view_order.ts +7 -3
  258. package/dist/templates/podcast-digest-workflow/agent.test.ts +53 -102
  259. package/dist/templates/podcast-digest-workflow/agent.ts +11 -17
  260. package/dist/templates/podcast-digest-workflow/client.tsx +29 -51
  261. package/dist/templates/podcast-digest-workflow/workflows/digest.ts +24 -26
  262. package/dist/templates/push-to-talk-agent/agent.eval.test.ts +13 -14
  263. package/dist/templates/push-to-talk-agent/agent.test.ts +30 -23
  264. package/dist/templates/push-to-talk-agent/agent.ts +1 -5
  265. package/dist/templates/push-to-talk-agent/client.tsx +1 -11
  266. package/dist/templates/push-to-talk-agent/shared.ts +12 -6
  267. package/dist/templates/push-to-talk-agent/tools/list_notes.ts +1 -0
  268. package/dist/templates/push-to-talk-agent/tools/save_note.ts +1 -0
  269. package/dist/templates/quickstart-agent/agent.eval.test.ts +0 -10
  270. package/dist/templates/quickstart-agent/agent.test.ts +18 -30
  271. package/dist/templates/quickstart-agent/agent.ts +3 -4
  272. package/dist/templates/research-handoff-agent/agent.eval.test.ts +161 -290
  273. package/dist/templates/research-handoff-agent/agent.test.ts +133 -471
  274. package/dist/templates/research-handoff-agent/agent.ts +26 -86
  275. package/dist/templates/research-handoff-agent/system-prompt.md +1 -0
  276. package/dist/templates/research-handoff-agent/tools/file_it_now.ts +8 -21
  277. package/dist/templates/research-handoff-agent/tools/request_research.ts +7 -16
  278. package/dist/templates/research-handoff-agent/workflows/research.ts +88 -40
  279. package/dist/templates/research-planner-agent/agent.eval.test.ts +15 -40
  280. package/dist/templates/research-planner-agent/agent.test.ts +415 -464
  281. package/dist/templates/research-planner-agent/agent.ts +3 -8
  282. package/dist/templates/research-planner-agent/client.tsx +1 -14
  283. package/dist/templates/research-planner-agent/procedure.ts +9 -3
  284. package/dist/templates/research-planner-agent/shared.ts +30 -33
  285. package/dist/templates/research-planner-agent/tools/plan_status.ts +7 -15
  286. package/dist/templates/research-planner-agent/tools/revise_plan.ts +29 -36
  287. package/dist/templates/research-planner-agent/tools/start_plan.ts +25 -39
  288. package/dist/templates/research-planner-agent/tools/work_next_step.ts +25 -42
  289. package/dist/templates/retail-orders-agent/agent.eval.test.ts +14 -34
  290. package/dist/templates/retail-orders-agent/agent.test.ts +1079 -1073
  291. package/dist/templates/retail-orders-agent/agent.ts +25 -78
  292. package/dist/templates/retail-orders-agent/client.tsx +120 -168
  293. package/dist/templates/retail-orders-agent/pending.test.ts +7 -14
  294. package/dist/templates/retail-orders-agent/registry.test.ts +93 -192
  295. package/dist/templates/retail-orders-agent/shared.test.ts +1 -1
  296. package/dist/templates/retail-orders-agent/shared.ts +10 -20
  297. package/dist/templates/retail-orders-agent/store.test.ts +46 -128
  298. package/dist/templates/retail-orders-agent/store.ts +42 -175
  299. package/dist/templates/retail-orders-agent/tools/cancel_change.ts +3 -6
  300. package/dist/templates/retail-orders-agent/tools/cancel_pending_order.ts +3 -4
  301. package/dist/templates/retail-orders-agent/tools/confirm_change.ts +4 -6
  302. package/dist/templates/retail-orders-agent/tools/exchange_delivered_order_items.ts +3 -4
  303. package/dist/templates/retail-orders-agent/tools/find_user_id_by_email.ts +3 -4
  304. package/dist/templates/retail-orders-agent/tools/find_user_id_by_name_zip.ts +3 -4
  305. package/dist/templates/retail-orders-agent/tools/get_item_details.ts +3 -4
  306. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +3 -4
  307. package/dist/templates/retail-orders-agent/tools/get_product_details.ts +3 -4
  308. package/dist/templates/retail-orders-agent/tools/get_user_details.ts +3 -4
  309. package/dist/templates/retail-orders-agent/tools/list_all_product_types.ts +3 -8
  310. package/dist/templates/retail-orders-agent/tools/modify_pending_order_address.ts +3 -4
  311. package/dist/templates/retail-orders-agent/tools/modify_pending_order_items.ts +3 -4
  312. package/dist/templates/retail-orders-agent/tools/modify_pending_order_payment.ts +3 -4
  313. package/dist/templates/retail-orders-agent/tools/modify_user_address.ts +3 -4
  314. package/dist/templates/retail-orders-agent/tools/return_delivered_order_items.ts +3 -4
  315. package/dist/templates/retail-orders-agent/tools/transfer_to_human_agents.ts +3 -4
  316. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +22 -25
  317. package/dist/templates/roadside-assistance-agent/agent.test.ts +453 -490
  318. package/dist/templates/roadside-assistance-agent/agent.ts +28 -60
  319. package/dist/templates/roadside-assistance-agent/call.ts +16 -22
  320. package/dist/templates/roadside-assistance-agent/shared.ts +24 -54
  321. package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +29 -37
  322. package/dist/templates/roadside-assistance-agent/tools/dispatch_truck.ts +44 -70
  323. package/dist/templates/roadside-assistance-agent/tools/job_status.ts +16 -24
  324. package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +39 -51
  325. package/dist/templates/roadside-assistance-agent/tools/report_location.ts +34 -33
  326. package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +18 -39
  327. package/dist/templates/roadside-assistance-agent/yard.test.ts +22 -19
  328. package/dist/templates/roadside-assistance-agent/yard.ts +3 -3
  329. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +38 -40
  330. package/dist/templates/spoken-summary-workflow/agent.test.ts +129 -279
  331. package/dist/templates/spoken-summary-workflow/agent.ts +15 -40
  332. package/dist/templates/spoken-summary-workflow/client.tsx +13 -25
  333. package/dist/templates/spoken-summary-workflow/workflows/summarize.ts +52 -92
  334. package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +31 -74
  335. package/dist/templates/tabletop-rpg-agent/agent.test.ts +756 -774
  336. package/dist/templates/tabletop-rpg-agent/agent.ts +9 -46
  337. package/dist/templates/tabletop-rpg-agent/client.tsx +13 -21
  338. package/dist/templates/tabletop-rpg-agent/shared.ts +40 -99
  339. package/dist/templates/tabletop-rpg-agent/tools/action_roll.ts +67 -83
  340. package/dist/templates/tabletop-rpg-agent/tools/burn_momentum.ts +65 -88
  341. package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +8 -27
  342. package/dist/templates/tabletop-rpg-agent/tools/setup_character.ts +18 -36
  343. package/dist/templates/tabletop-rpg-agent/tools/update_state.ts +101 -111
  344. package/dist/templates/technical-support-agent/agent.eval.test.ts +31 -72
  345. package/dist/templates/technical-support-agent/agent.test.ts +231 -260
  346. package/dist/templates/technical-support-agent/agent.ts +4 -10
  347. package/dist/templates/technical-support-agent/client.tsx +4 -18
  348. package/dist/templates/technical-support-agent/shared.ts +15 -25
  349. package/dist/templates/technical-support-agent/tools/answer_question.ts +46 -56
  350. package/dist/templates/technical-support-agent/tools/list_topics.ts +1 -0
  351. package/dist/templates/technical-support-agent/tools/log_ticket.ts +8 -5
  352. package/dist/templates/text-adventure-agent/agent.eval.test.ts +37 -126
  353. package/dist/templates/text-adventure-agent/agent.test.ts +197 -368
  354. package/dist/templates/text-adventure-agent/agent.ts +15 -65
  355. package/dist/templates/text-adventure-agent/client.tsx +38 -98
  356. package/dist/templates/text-adventure-agent/shared.ts +31 -143
  357. package/dist/templates/text-adventure-agent/tools/game_state_drop.ts +6 -12
  358. package/dist/templates/text-adventure-agent/tools/game_state_get.ts +4 -11
  359. package/dist/templates/text-adventure-agent/tools/game_state_move.ts +0 -2
  360. package/dist/templates/text-adventure-agent/tools/game_state_restart.ts +1 -3
  361. package/dist/templates/text-adventure-agent/tools/game_state_score.ts +5 -7
  362. package/dist/templates/topic-briefing-agent/agent.eval.test.ts +12 -50
  363. package/dist/templates/topic-briefing-agent/agent.test.ts +478 -476
  364. package/dist/templates/topic-briefing-agent/agent.ts +3 -3
  365. package/dist/templates/topic-briefing-agent/shared.ts +11 -16
  366. package/dist/templates/topic-briefing-agent/slack.ts +12 -4
  367. package/dist/templates/topic-briefing-agent/tools/briefing_so_far.ts +10 -17
  368. package/dist/templates/topic-briefing-agent/tools/research_topic.ts +21 -24
  369. package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +13 -14
  370. package/dist/templates/topic-briefing-agent/tools/verify_claim.ts +16 -13
  371. package/dist/templates/transcription-workflow/agent.test.ts +114 -259
  372. package/dist/templates/transcription-workflow/agent.ts +6 -9
  373. package/dist/templates/transcription-workflow/client.tsx +100 -258
  374. package/dist/templates/transcription-workflow/recover.test.ts +6 -136
  375. package/dist/templates/transcription-workflow/recover.ts +14 -97
  376. package/dist/templates/transcription-workflow/run-panel.tsx +71 -8
  377. package/dist/templates/transcription-workflow/workflows/batch.ts +28 -159
  378. package/dist/templates/transcription-workflow/workflows/normalize.ts +50 -86
  379. package/dist/templates/transcription-workflow/workflows/stream.ts +2 -2
  380. package/dist/templates/transcription-workflow/workflows/transcribe.ts +16 -23
  381. package/dist/templates/travel-concierge-agent/agent.eval.test.ts +7 -25
  382. package/dist/templates/travel-concierge-agent/agent.test.ts +505 -517
  383. package/dist/templates/travel-concierge-agent/agent.ts +22 -46
  384. package/dist/templates/travel-concierge-agent/client.tsx +1 -22
  385. package/dist/templates/travel-concierge-agent/routing.ts +29 -31
  386. package/dist/templates/travel-concierge-agent/shared.ts +63 -152
  387. package/dist/templates/travel-concierge-agent/tools/book_car_rental.ts +8 -9
  388. package/dist/templates/travel-concierge-agent/tools/book_excursion.ts +8 -8
  389. package/dist/templates/travel-concierge-agent/tools/book_hotel.ts +9 -6
  390. package/dist/templates/travel-concierge-agent/tools/cancel_ticket.ts +10 -10
  391. package/dist/templates/travel-concierge-agent/tools/search_car_rentals.ts +3 -2
  392. package/dist/templates/travel-concierge-agent/tools/search_excursions.ts +3 -2
  393. package/dist/templates/travel-concierge-agent/tools/search_flights.ts +4 -3
  394. package/dist/templates/travel-concierge-agent/tools/search_hotels.ts +3 -2
  395. package/dist/templates/travel-concierge-agent/tools/update_ticket.ts +13 -8
  396. package/dist/templates/web-research-agent/agent.test.ts +21 -32
  397. package/dist/templates/web-research-agent/agent.ts +3 -4
  398. package/dist/templates/word-game-agent/agent.eval.test.ts +47 -67
  399. package/dist/templates/word-game-agent/agent.test.ts +369 -382
  400. package/dist/templates/word-game-agent/agent.ts +2 -5
  401. package/dist/templates/word-game-agent/client.tsx +1 -8
  402. package/dist/templates/word-game-agent/game.ts +15 -27
  403. package/dist/templates/word-game-agent/shared.ts +36 -20
  404. package/dist/templates/word-game-agent/tools/final_score.ts +14 -13
  405. package/dist/templates/word-game-agent/tools/relay_description.ts +90 -66
  406. package/dist/templates/word-game-agent/tools/repeat_word.ts +11 -10
  407. package/dist/templates/word-game-agent/tools/skip_word.ts +17 -21
  408. package/dist/templates/word-game-agent/tools/start_game.ts +26 -30
  409. package/dist/{test-XufelYGW.mjs → test-CW5cw5fy.mjs} +3 -4
  410. package/dist/typecheck.mjs +1 -1
  411. package/dist/worker-bundler-D8uCzpYP.mjs +335 -0
  412. package/dist/worker-bundler.d.ts +39 -0
  413. package/dist/worker-bundler.mjs +2 -155
  414. package/dist/{workflow-CDUlTD5B.mjs → workflow-5gOZMB2M.mjs} +66 -19
  415. package/package.json +4 -4
  416. package/dist/_output-DBP9Op_d.mjs +0 -120
  417. package/dist/_studio-B5m4jBTD.mjs +0 -256
  418. package/dist/_ui-Coe0zwmm.mjs +0 -102
  419. package/dist/_utils-BVLdBvdT.mjs +0 -186
  420. package/dist/delete-DwXCHzTl.mjs +0 -55
  421. package/dist/templates/document-redline-workflow/form.ts +0 -74
  422. package/dist/templates/emergency-dispatch-agent/events.ts +0 -48
  423. package/dist/templates/hotel-reception-agent/events.ts +0 -80
  424. package/dist/templates/meeting-recap-agent/shared.ts +0 -44
  425. package/dist/templates/meeting-recap-agent/tools/cancel_recap.ts +0 -25
  426. package/dist/templates/meeting-recap-agent/tools/recap_progress.ts +0 -24
  427. package/dist/templates/meeting-recap-agent/tools/recap_status.ts +0 -45
  428. package/dist/templates/meeting-recap-agent/workflows/tokens.ts +0 -47
  429. package/dist/templates/outbound-call-agent/call-params.ts +0 -109
  430. package/dist/templates/outbound-call-agent/live-calls.ts +0 -80
  431. package/dist/templates/outbound-call-agent/workflows/tokens.ts +0 -16
  432. package/dist/templates/research-handoff-agent/shared.ts +0 -41
  433. package/dist/templates/research-handoff-agent/tools/research_progress.ts +0 -23
  434. package/dist/templates/research-handoff-agent/tools/research_status.ts +0 -73
  435. package/dist/templates/research-handoff-agent/workflows/review.ts +0 -43
  436. package/dist/templates/roadside-assistance-agent/events.ts +0 -92
  437. package/dist/templates/spoken-summary-workflow/workflows/transcribe.ts +0 -137
  438. package/dist/templates/transcription-workflow/total-latency.tsx +0 -170
  439. package/dist/templates/travel-concierge-agent/call-events.ts +0 -80
@@ -1,14 +1,15 @@
1
+ import agentDef from "virtual:aai/agent";
1
2
  import type { ToolContext } from "@alexkroman1/aai";
2
3
  import { isToolFailure } from "@alexkroman1/aai";
3
4
  import {
4
5
  createToolContext,
5
6
  expectDialogRefused,
6
7
  expectToolOk,
8
+ fireEvent,
9
+ sessionEvent,
7
10
  } from "@alexkroman1/aai-runtime/testing";
11
+ import { describeAgent } from "@alexkroman1/aai-runtime/testing/vitest";
8
12
  import { describe, expect, test } from "vitest";
9
- import type { AuthResult } from "./authenticate.ts";
10
- import type { StagedResult } from "./pending.ts";
11
- import type { Address } from "./shared.ts";
12
13
  import { callFlow, retailSlot } from "./store.ts";
13
14
  import cancelPendingOrder from "./tools/cancel_pending_order.ts";
14
15
  import confirmChange from "./tools/confirm_change.ts";
@@ -27,1234 +28,1239 @@ import modifyUserAddress from "./tools/modify_user_address.ts";
27
28
  import returnDeliveredOrderItems from "./tools/return_delivered_order_items.ts";
28
29
  import transferToHumanAgents from "./tools/transfer_to_human_agents.ts";
29
30
 
30
- /** A context already authenticated as `userId`, via the real tool. */
31
- async function authedCtx(email: string): Promise<ToolContext> {
32
- const ctx = createToolContext();
33
- expectToolOk<AuthResult>(await findUserIdByEmail.execute({ email }, ctx));
34
- return ctx;
35
- }
36
-
37
- /**
38
- * Stage a change and say yes — the two calls one caller turn now produces.
39
- *
40
- * Nothing in this template mutates before `confirm_change`, so every spec about
41
- * an APPLIED change has to run both halves. That is not helper ceremony: it is
42
- * the property under test, and a spec that forgot the second call would find
43
- * the store untouched. It asserts the readback exists on the way through,
44
- * because a staged change the agent has no sentence for is the one shape that
45
- * would let this gate pass while carrying nothing to confirm.
46
- */
47
- async function confirmed<R = unknown>(staged: unknown, ctx: ToolContext): Promise<R> {
48
- const stage = expectToolOk<StagedResult>(staged);
49
- // A throw rather than an `expect`, which biome's `noMisplacedAssertion`
50
- // rightly refuses outside a test body. A staged change with no sentence to
51
- // read back is the one shape that would let the gate pass while carrying
52
- // nothing to confirm, so it stops the spec here rather than downstream.
53
- if (stage.read_back.length === 0) throw new Error(`${stage.staged} staged with no readback`);
54
- return expectToolOk<R>(await confirmChange.execute({}, ctx));
55
- }
56
-
57
- describe("authentication", () => {
58
- test("find_user_id_by_email is case-insensitive and authenticates the session", async () => {
31
+ // The slot's contract (`expectSlotContract`: the empty frame, isolation, the
32
+ // cap) is asserted in `registry.test.ts`, beside the lowering it belongs to.
33
+ describeAgent(agentDef, (run) => {
34
+ /** A context already authenticated as `userId`, via the real tool. */
35
+ async function authedCtx(email: string): Promise<ToolContext> {
59
36
  const ctx = createToolContext();
60
- const result = expectToolOk<AuthResult>(
61
- await findUserIdByEmail.execute({ email: "OLIVIA.ITO5204@EXAMPLE.COM" }, ctx),
62
- );
63
- expect(result.user_id).toBe("olivia_ito_3591");
64
- expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
65
- // Two facts, two homes: the store latches WHO, the flow holds WHETHER.
66
- // `serving` is a parent now, so an identified call reports its child.
67
- expect(callFlow.position(ctx).state).toBe("serving.helping");
68
- });
37
+ expectToolOk(await run(findUserIdByEmail, { email }, ctx));
38
+ return ctx;
39
+ }
40
+
41
+ /**
42
+ * Stage a change and say yes — the two calls one caller turn now produces.
43
+ *
44
+ * Nothing in this template mutates before `confirm_change`, so every spec about
45
+ * an APPLIED change has to run both halves. That is not helper ceremony: it is
46
+ * the property under test, and a spec that forgot the second call would find
47
+ * the store untouched. It asserts the readback exists on the way through,
48
+ * because a staged change the agent has no sentence for is the one shape that
49
+ * would let this gate pass while carrying nothing to confirm.
50
+ */
51
+ async function confirmed<R extends Confirmed = Confirmed>(
52
+ staged: Staged,
53
+ ctx: ToolContext,
54
+ ): Promise<R> {
55
+ const stage = expectToolOk(staged);
56
+ // A throw rather than an `expect`, which biome's `noMisplacedAssertion`
57
+ // rightly refuses outside a test body. A staged change with no sentence to
58
+ // read back is the one shape that would let the gate pass while carrying
59
+ // nothing to confirm, so it stops the spec here rather than downstream.
60
+ if (stage.read_back.length === 0) throw new Error(`${stage.staged} staged with no readback`);
61
+ // The def answers every arm `applyAction` has; the caller names the one it staged.
62
+ return (await applied(ctx)) as R;
63
+ }
64
+
65
+ /** What any staging tool answers — the same envelope from all seven. */
66
+ type Staged = Awaited<ReturnType<typeof cancelPendingOrder.execute>>;
67
+
68
+ /** `confirm_change`'s answer, unwrapped: the def's own type, every arm of `applyAction`. */
69
+ const applied = async (ctx: ToolContext) => expectToolOk(await run(confirmChange, ctx));
70
+ type Confirmed = Awaited<ReturnType<typeof applied>>;
71
+
72
+ describe("authentication", () => {
73
+ test("find_user_id_by_email is case-insensitive and authenticates the session", async () => {
74
+ const ctx = createToolContext();
75
+ const result = expectToolOk(
76
+ await run(findUserIdByEmail, { email: "OLIVIA.ITO5204@EXAMPLE.COM" }, ctx),
77
+ );
78
+ expect(result.user_id).toBe("olivia_ito_3591");
79
+ expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
80
+ // Two facts, two homes: the store latches WHO, the flow holds WHETHER.
81
+ // `serving` is a parent now, so an identified call reports its child.
82
+ expect(callFlow.position(ctx).state).toBe("serving.helping");
83
+ });
69
84
 
70
- test("an unknown email is refused and leaves the session unauthenticated", async () => {
71
- const ctx = createToolContext();
72
- const result = await findUserIdByEmail.execute({ email: "nobody@example.com" }, ctx);
73
- expect(isToolFailure(result)).toBe(true);
74
- expect(retailSlot.get(ctx).authenticatedUserId).toBeNull();
75
- // `IDENTIFIED` is not sent when the body answers a `ToolFailure`, so a
76
- // lookup that found nobody cannot leave the call one step ahead of itself.
77
- expect(callFlow.position(ctx).state).toBe("identifying");
78
- });
85
+ test("an unknown email is refused and leaves the session unauthenticated", async () => {
86
+ const ctx = createToolContext();
87
+ const result = await run(findUserIdByEmail, { email: "nobody@example.com" }, ctx);
88
+ expect(isToolFailure(result)).toBe(true);
89
+ expect(retailSlot.get(ctx).authenticatedUserId).toBeNull();
90
+ // `IDENTIFIED` is not sent when the body answers a `ToolFailure`, so a
91
+ // lookup that found nobody cannot leave the call one step ahead of itself.
92
+ expect(callFlow.position(ctx).state).toBe("identifying");
93
+ });
79
94
 
80
- test("find_user_id_by_name_zip is case-insensitive on names and exact on zip", async () => {
81
- const ctx = createToolContext();
82
- const found = expectToolOk<AuthResult>(
83
- await findUserIdByNameZip.execute(
84
- { first_name: "aarav", last_name: "ANDERSON", zip: "19031" },
85
- ctx,
86
- ),
87
- );
88
- expect(found.user_id).toBe("aarav_anderson_8794");
95
+ test("find_user_id_by_name_zip is case-insensitive on names and exact on zip", async () => {
96
+ const ctx = createToolContext();
97
+ const found = expectToolOk(
98
+ await run(
99
+ findUserIdByNameZip,
100
+ { first_name: "aarav", last_name: "ANDERSON", zip: "19031" },
101
+ ctx,
102
+ ),
103
+ );
104
+ expect(found.user_id).toBe("aarav_anderson_8794");
105
+
106
+ const wrongZip = await run(
107
+ findUserIdByNameZip,
108
+ { first_name: "Aarav", last_name: "Anderson", zip: "78268" },
109
+ createToolContext(),
110
+ );
111
+ expect(isToolFailure(wrongZip)).toBe(true);
112
+ });
89
113
 
90
- const wrongZip = await findUserIdByNameZip.execute(
91
- { first_name: "Aarav", last_name: "Anderson", zip: "78268" },
92
- createToolContext(),
93
- );
94
- expect(isToolFailure(wrongZip)).toBe(true);
95
- });
114
+ test("two customers share a first name — the zip is what separates them", async () => {
115
+ const a = expectToolOk(
116
+ await run(
117
+ findUserIdByNameZip,
118
+ { first_name: "Aarav", last_name: "Anderson", zip: "19031" },
119
+ createToolContext(),
120
+ ),
121
+ );
122
+ const b = expectToolOk(
123
+ await run(
124
+ findUserIdByNameZip,
125
+ { first_name: "Aarav", last_name: "Gonzalez", zip: "78268" },
126
+ createToolContext(),
127
+ ),
128
+ );
129
+ expect(a.user_id).toBe("aarav_anderson_8794");
130
+ expect(b.user_id).toBe("aarav_gonzalez_5113");
131
+ });
132
+
133
+ test("re-authenticating as the same customer is a no-op success", async () => {
134
+ const ctx = await authedCtx("olivia.ito5204@example.com");
135
+ const again = await run(findUserIdByEmail, { email: "olivia.ito5204@example.com" }, ctx);
136
+ expect(isToolFailure(again)).toBe(false);
137
+ expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
138
+ });
96
139
 
97
- test("two customers share a first name — the zip is what separates them", async () => {
98
- const a = expectToolOk<AuthResult>(
99
- await findUserIdByNameZip.execute(
140
+ test("switching to a DIFFERENT customer mid-conversation is refused", async () => {
141
+ const ctx = await authedCtx("olivia.ito5204@example.com");
142
+ const switched = await run(
143
+ findUserIdByEmail,
144
+ { email: "aarav.anderson9752@example.com" },
145
+ ctx,
146
+ );
147
+ expect(isToolFailure(switched) && switched.error.toLowerCase()).toContain("one customer");
148
+ expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
149
+ // The tool is legal in `serving` — the refusal comes from `authenticateAs`,
150
+ // not from the gate — so the call stays exactly where it was.
151
+ expect(callFlow.position(ctx).state).toBe("serving.helping");
152
+ });
153
+
154
+ test("switching via name + zip is refused too — both doors, one lock", async () => {
155
+ const ctx = await authedCtx("olivia.ito5204@example.com");
156
+ const switched = await run(
157
+ findUserIdByNameZip,
100
158
  { first_name: "Aarav", last_name: "Anderson", zip: "19031" },
101
- createToolContext(),
102
- ),
103
- );
104
- const b = expectToolOk<AuthResult>(
105
- await findUserIdByNameZip.execute(
106
- { first_name: "Aarav", last_name: "Gonzalez", zip: "78268" },
107
- createToolContext(),
108
- ),
109
- );
110
- expect(a.user_id).toBe("aarav_anderson_8794");
111
- expect(b.user_id).toBe("aarav_gonzalez_5113");
159
+ ctx,
160
+ );
161
+ expect(isToolFailure(switched)).toBe(true);
162
+ expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
163
+ });
112
164
  });
113
165
 
114
- test("re-authenticating as the same customer is a no-op success", async () => {
115
- const ctx = await authedCtx("olivia.ito5204@example.com");
116
- const again = await findUserIdByEmail.execute({ email: "olivia.ito5204@example.com" }, ctx);
117
- expect(isToolFailure(again)).toBe(false);
118
- expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
119
- });
166
+ describe("read tools", () => {
167
+ test("get_user_details returns the caller's profile with gift-card balances", async () => {
168
+ const ctx = await authedCtx("olivia.ito5204@example.com");
169
+ const result = expectToolOk(await run(getUserDetails, { user_id: "olivia_ito_3591" }, ctx));
170
+ expect(result.email).toBe("olivia.ito5204@example.com");
171
+ expect(result.orders).toHaveLength(5);
172
+ const card = result.payment_methods.find((m) => m.payment_method_id === "gift_card_7794233");
173
+ expect(card?.balance).toBe(56);
174
+ });
120
175
 
121
- test("switching to a DIFFERENT customer mid-conversation is refused", async () => {
122
- const ctx = await authedCtx("olivia.ito5204@example.com");
123
- const switched = await findUserIdByEmail.execute(
124
- { email: "aarav.anderson9752@example.com" },
125
- ctx,
126
- );
127
- expect(isToolFailure(switched) && switched.error.toLowerCase()).toContain("one customer");
128
- expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
129
- // The tool is legal in `serving` — the refusal comes from `authenticateAs`,
130
- // not from the gate — so the call stays exactly where it was.
131
- expect(callFlow.position(ctx).state).toBe("serving.helping");
132
- });
176
+ test("get_user_details refuses a different user id", async () => {
177
+ const ctx = await authedCtx("olivia.ito5204@example.com");
178
+ const result = await run(getUserDetails, { user_id: "aarav_anderson_8794" }, ctx);
179
+ expect(isToolFailure(result)).toBe(true);
180
+ });
133
181
 
134
- test("switching via name + zip is refused too — both doors, one lock", async () => {
135
- const ctx = await authedCtx("olivia.ito5204@example.com");
136
- const switched = await findUserIdByNameZip.execute(
137
- { first_name: "Aarav", last_name: "Anderson", zip: "19031" },
138
- ctx,
139
- );
140
- expect(isToolFailure(switched)).toBe(true);
141
- expect(retailSlot.get(ctx).authenticatedUserId).toBe("olivia_ito_3591");
142
- });
143
- });
182
+ test("get_order_details resolves shorthand and sets focus", async () => {
183
+ const ctx = await authedCtx("olivia.ito5204@example.com");
184
+ const result = expectToolOk(
185
+ await run(getOrderDetails, { order_id: "the delivered one" }, ctx),
186
+ );
187
+ expect(result.order_id).toBe("#W5866402");
188
+ expect(retailSlot.get(ctx).focus.orderId).toBe("#W5866402");
189
+ });
144
190
 
145
- interface UserDetailsResult {
146
- user_id: string;
147
- email: string;
148
- orders: { order_id: string; status: string }[];
149
- payment_methods: { payment_method_id: string; source: string; balance?: number }[];
150
- }
151
-
152
- interface OrderDetailsResult {
153
- order_id: string;
154
- }
155
-
156
- interface ProductDetailsResult {
157
- name: string;
158
- variants: { item_id: string }[];
159
- }
160
-
161
- interface ItemDetailsResult {
162
- price: number;
163
- product_name: string;
164
- }
165
-
166
- interface ProductTypesResult {
167
- products: Record<string, string>;
168
- }
169
-
170
- describe("read tools", () => {
171
- test("get_user_details returns the caller's profile with gift-card balances", async () => {
172
- const ctx = await authedCtx("olivia.ito5204@example.com");
173
- const result = expectToolOk<UserDetailsResult>(
174
- await getUserDetails.execute({ user_id: "olivia_ito_3591" }, ctx),
175
- );
176
- expect(result.email).toBe("olivia.ito5204@example.com");
177
- expect(result.orders).toHaveLength(5);
178
- const card = result.payment_methods.find((m) => m.payment_method_id === "gift_card_7794233");
179
- expect(card?.balance).toBe(56);
180
- });
191
+ test("get_order_details refuses another customer's order", async () => {
192
+ const ctx = await authedCtx("olivia.ito5204@example.com");
193
+ const result = await run(getOrderDetails, { order_id: "#W4316152" }, ctx);
194
+ expect(isToolFailure(result)).toBe(true);
195
+ });
181
196
 
182
- test("get_user_details refuses a different user id", async () => {
183
- const ctx = await authedCtx("olivia.ito5204@example.com");
184
- const result = await getUserDetails.execute({ user_id: "aarav_anderson_8794" }, ctx);
185
- expect(isToolFailure(result)).toBe(true);
186
- });
197
+ test("get_product_details lists variants and needs no authentication", async () => {
198
+ const result = expectToolOk(
199
+ await run(getProductDetails, { product_id: "9832717871" }, createToolContext()),
200
+ );
201
+ expect(result.name).toBe("Tea Kettle");
202
+ expect(result.variants.length).toBeGreaterThan(1);
203
+ expect(result.variants[0]).toHaveProperty("item_id");
204
+ });
187
205
 
188
- test("get_order_details resolves shorthand and sets focus", async () => {
189
- const ctx = await authedCtx("olivia.ito5204@example.com");
190
- const result = expectToolOk<OrderDetailsResult>(
191
- await getOrderDetails.execute({ order_id: "the delivered one" }, ctx),
192
- );
193
- expect(result.order_id).toBe("#W5866402");
194
- expect(retailSlot.get(ctx).focus.orderId).toBe("#W5866402");
195
- });
206
+ test("get_product_details rejects an item id passed as a product id, and says so", async () => {
207
+ const result = await run(
208
+ getProductDetails,
209
+ { product_id: "3909406921" },
210
+ createToolContext(),
211
+ );
212
+ expect(isToolFailure(result) && result.error).toContain("item id");
213
+ });
196
214
 
197
- test("get_order_details refuses another customer's order", async () => {
198
- const ctx = await authedCtx("olivia.ito5204@example.com");
199
- const result = await getOrderDetails.execute({ order_id: "#W4316152" }, ctx);
200
- expect(isToolFailure(result)).toBe(true);
201
- });
215
+ test("get_item_details resolves an item without knowing its product", async () => {
216
+ const result = expectToolOk(
217
+ await run(getItemDetails, { item_id: "3909406921" }, createToolContext()),
218
+ );
219
+ expect(result.price).toBe(98.25);
220
+ expect(result.product_name).toBe("Tea Kettle");
221
+ });
202
222
 
203
- test("get_product_details lists variants and needs no authentication", async () => {
204
- const result = expectToolOk<ProductDetailsResult>(
205
- await getProductDetails.execute({ product_id: "9832717871" }, createToolContext()),
206
- );
207
- expect(result.name).toBe("Tea Kettle");
208
- expect(result.variants.length).toBeGreaterThan(1);
209
- expect(result.variants[0]).toHaveProperty("item_id");
223
+ test("list_all_product_types returns all 50, sorted by name", async () => {
224
+ const result = expectToolOk(await run(listAllProductTypes, createToolContext()));
225
+ expect(Object.keys(result.products)).toHaveLength(50);
226
+ const names = Object.keys(result.products);
227
+ // localeCompare, not the default lexicographic sort — the tool sorts for a
228
+ // human reading the catalog, e.g. "Laptop" before "LED Light Bulb" ('a' < 'E'
229
+ // by locale, but not by UTF-16 code unit).
230
+ expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)));
231
+ });
210
232
  });
211
233
 
212
- test("get_product_details rejects an item id passed as a product id, and says so", async () => {
213
- const result = await getProductDetails.execute(
214
- { product_id: "3909406921" },
215
- createToolContext(),
216
- );
217
- expect(isToolFailure(result) && result.error).toContain("item id");
218
- });
234
+ type CancelOrderResult = Extract<Confirmed, { cancel_reason: unknown }>;
219
235
 
220
- test("get_item_details resolves an item without knowing its product", async () => {
221
- const result = expectToolOk<ItemDetailsResult>(
222
- await getItemDetails.execute({ item_id: "3909406921" }, createToolContext()),
223
- );
224
- expect(result.price).toBe(98.25);
225
- expect(result.product_name).toBe("Tea Kettle");
226
- });
236
+ describe("cancel_pending_order", () => {
237
+ test("cancels a pending order and credits a gift card immediately", async () => {
238
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
239
+ const result = await confirmed<CancelOrderResult>(
240
+ await run(cancelPendingOrder, { order_id: "#W9300146", reason: "ordered by mistake" }, ctx),
241
+ ctx,
242
+ );
243
+ expect(result.status).toBe("cancelled");
244
+ expect(result.refund_immediate).toBe(true);
245
+
246
+ const state = retailSlot.get(ctx);
247
+ expect(state.store.orders["#W9300146"]?.status).toBe("cancelled");
248
+ expect(state.store.orders["#W9300146"]?.cancel_reason).toBe("ordered by mistake");
249
+ // $17.00 card + the $153.23 order total.
250
+ const card = state.store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
251
+ expect(card?.source === "gift_card" && card.balance).toBe(170.23);
252
+ });
227
253
 
228
- test("list_all_product_types returns all 50, sorted by name", async () => {
229
- const result = expectToolOk<ProductTypesResult>(
230
- await listAllProductTypes.execute({}, createToolContext()),
231
- );
232
- expect(Object.keys(result.products)).toHaveLength(50);
233
- const names = Object.keys(result.products);
234
- // localeCompare, not the default lexicographic sort — the tool sorts for a
235
- // human reading the catalog, e.g. "Laptop" before "LED Light Bulb" ('a' < 'E'
236
- // by locale, but not by UTF-16 code unit).
237
- expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b)));
238
- });
239
- });
254
+ test("appends a matching refund to the payment history", async () => {
255
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
256
+ await confirmed(
257
+ await run(cancelPendingOrder, { order_id: "#W9300146", reason: "no longer needed" }, ctx),
258
+ ctx,
259
+ );
260
+ const history = retailSlot.get(ctx).store.orders["#W9300146"]?.payment_history ?? [];
261
+ expect(history).toHaveLength(2);
262
+ expect(history[1]).toMatchObject({
263
+ transaction_type: "refund",
264
+ amount: 153.23,
265
+ payment_method_id: "gift_card_7245904",
266
+ });
267
+ });
240
268
 
241
- interface CancelOrderResult {
242
- order_id: string;
243
- status: string;
244
- cancel_reason: string;
245
- refunded: number;
246
- refund_immediate: boolean;
247
- message: string;
248
- }
249
-
250
- describe("cancel_pending_order", () => {
251
- test("cancels a pending order and credits a gift card immediately", async () => {
252
- const ctx = await authedCtx("aarav.anderson9752@example.com");
253
- const result = await confirmed<CancelOrderResult>(
254
- await cancelPendingOrder.execute(
255
- { order_id: "#W9300146", reason: "ordered by mistake" },
269
+ test("a non-gift-card refund takes 5-7 days and moves no balance", async () => {
270
+ const ctx = await authedCtx("olivia.ito5204@example.com");
271
+ const result = await confirmed<CancelOrderResult>(
272
+ await run(cancelPendingOrder, { order_id: "#W5442520", reason: "no longer needed" }, ctx),
256
273
  ctx,
257
- ),
258
- ctx,
259
- );
260
- expect(result.status).toBe("cancelled");
261
- expect(result.refund_immediate).toBe(true);
262
-
263
- const state = retailSlot.get(ctx);
264
- expect(state.store.orders["#W9300146"]?.status).toBe("cancelled");
265
- expect(state.store.orders["#W9300146"]?.cancel_reason).toBe("ordered by mistake");
266
- // $17.00 card + the $153.23 order total.
267
- const card = state.store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
268
- expect(card?.source === "gift_card" && card.balance).toBe(170.23);
269
- });
274
+ );
275
+ expect(result.refund_immediate).toBe(false);
276
+ expect(result.message).toContain("5 to 7");
277
+ const card =
278
+ retailSlot.get(ctx).store.users.olivia_ito_3591?.payment_methods.gift_card_7794233;
279
+ expect(card?.source === "gift_card" && card.balance).toBe(56);
280
+ });
270
281
 
271
- test("appends a matching refund to the payment history", async () => {
272
- const ctx = await authedCtx("aarav.anderson9752@example.com");
273
- await confirmed(
274
- await cancelPendingOrder.execute({ order_id: "#W9300146", reason: "no longer needed" }, ctx),
275
- ctx,
276
- );
277
- const history = retailSlot.get(ctx).store.orders["#W9300146"]?.payment_history ?? [];
278
- expect(history).toHaveLength(2);
279
- expect(history[1]).toMatchObject({
280
- transaction_type: "refund",
281
- amount: 153.23,
282
- payment_method_id: "gift_card_7245904",
282
+ test("refuses a processed order", async () => {
283
+ const ctx = await authedCtx("olivia.ito5204@example.com");
284
+ const result = await run(
285
+ cancelPendingOrder,
286
+ { order_id: "#W5353646", reason: "no longer needed" },
287
+ ctx,
288
+ );
289
+ expect(isToolFailure(result) && result.error).toContain("processed");
290
+ expect(retailSlot.get(ctx).store.orders["#W5353646"]?.status).toBe("processed");
283
291
  });
284
- });
285
292
 
286
- test("a non-gift-card refund takes 5-7 days and moves no balance", async () => {
287
- const ctx = await authedCtx("olivia.ito5204@example.com");
288
- const result = await confirmed<CancelOrderResult>(
289
- await cancelPendingOrder.execute({ order_id: "#W5442520", reason: "no longer needed" }, ctx),
290
- ctx,
291
- );
292
- expect(result.refund_immediate).toBe(false);
293
- expect(result.message).toContain("5 to 7");
294
- const card = retailSlot.get(ctx).store.users.olivia_ito_3591?.payment_methods.gift_card_7794233;
295
- expect(card?.source === "gift_card" && card.balance).toBe(56);
296
- });
293
+ test("refuses a delivered order", async () => {
294
+ const ctx = await authedCtx("olivia.ito5204@example.com");
295
+ const result = await run(
296
+ cancelPendingOrder,
297
+ { order_id: "#W5866402", reason: "no longer needed" },
298
+ ctx,
299
+ );
300
+ expect(isToolFailure(result)).toBe(true);
301
+ });
297
302
 
298
- test("refuses a processed order", async () => {
299
- const ctx = await authedCtx("olivia.ito5204@example.com");
300
- const result = await cancelPendingOrder.execute(
301
- { order_id: "#W5353646", reason: "no longer needed" },
302
- ctx,
303
- );
304
- expect(isToolFailure(result) && result.error).toContain("processed");
305
- expect(retailSlot.get(ctx).store.orders["#W5353646"]?.status).toBe("processed");
306
- });
303
+ test("refuses a reason outside tau2's two accepted values", async () => {
304
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
305
+ // The schema's `reason` field is a two-value enum, so a well-typed caller
306
+ // can never construct this input — this simulates the wire boundary
307
+ // (an LLM tool call is untyped) rather than a call TS would allow.
308
+ const result = await run(
309
+ cancelPendingOrder,
310
+ { order_id: "#W9300146", reason: "changed my mind" as unknown as "no longer needed" },
311
+ ctx,
312
+ );
313
+ expect(isToolFailure(result) && result.error).toContain("no longer needed");
314
+ expect(retailSlot.get(ctx).store.orders["#W9300146"]?.status).toBe("pending");
315
+ });
307
316
 
308
- test("refuses a delivered order", async () => {
309
- const ctx = await authedCtx("olivia.ito5204@example.com");
310
- const result = await cancelPendingOrder.execute(
311
- { order_id: "#W5866402", reason: "no longer needed" },
312
- ctx,
313
- );
314
- expect(isToolFailure(result)).toBe(true);
315
- });
317
+ test("refuses cancelling twice", async () => {
318
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
319
+ await confirmed(
320
+ await run(cancelPendingOrder, { order_id: "#W9300146", reason: "no longer needed" }, ctx),
321
+ ctx,
322
+ );
323
+ const second = await run(
324
+ cancelPendingOrder,
325
+ { order_id: "#W9300146", reason: "no longer needed" },
326
+ ctx,
327
+ );
328
+ expect(isToolFailure(second)).toBe(true);
329
+ const card =
330
+ retailSlot.get(ctx).store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
331
+ expect(card?.source === "gift_card" && card.balance).toBe(170.23);
332
+ });
316
333
 
317
- test("refuses a reason outside tau2's two accepted values", async () => {
318
- const ctx = await authedCtx("aarav.anderson9752@example.com");
319
- // The schema's `reason` field is a two-value enum, so a well-typed caller
320
- // can never construct this input — this simulates the wire boundary
321
- // (an LLM tool call is untyped) rather than a call TS would allow.
322
- const result = await cancelPendingOrder.execute(
323
- { order_id: "#W9300146", reason: "changed my mind" as unknown as "no longer needed" },
324
- ctx,
325
- );
326
- expect(isToolFailure(result) && result.error).toContain("no longer needed");
327
- expect(retailSlot.get(ctx).store.orders["#W9300146"]?.status).toBe("pending");
328
- });
334
+ test("resolves spoken shorthand to the single pending order", async () => {
335
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
336
+ const result = await confirmed<CancelOrderResult>(
337
+ await run(
338
+ cancelPendingOrder,
339
+ { order_id: "my pending order", reason: "ordered by mistake" },
340
+ ctx,
341
+ ),
342
+ ctx,
343
+ );
344
+ expect(result.order_id).toBe("#W9300146");
345
+ });
329
346
 
330
- test("refuses cancelling twice", async () => {
331
- const ctx = await authedCtx("aarav.anderson9752@example.com");
332
- await confirmed(
333
- await cancelPendingOrder.execute({ order_id: "#W9300146", reason: "no longer needed" }, ctx),
334
- ctx,
335
- );
336
- const second = await cancelPendingOrder.execute(
337
- { order_id: "#W9300146", reason: "no longer needed" },
338
- ctx,
339
- );
340
- expect(isToolFailure(second)).toBe(true);
341
- const card =
342
- retailSlot.get(ctx).store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
343
- expect(card?.source === "gift_card" && card.balance).toBe(170.23);
347
+ test("refuses ambiguous shorthand rather than cancelling the wrong order", async () => {
348
+ const ctx = await authedCtx("olivia.ito5204@example.com");
349
+ const result = await run(
350
+ cancelPendingOrder,
351
+ { order_id: "my pending order", reason: "no longer needed" },
352
+ ctx,
353
+ );
354
+ expect(isToolFailure(result)).toBe(true);
355
+ const statuses = ["#W5442520", "#W7941031", "#W3657213"].map(
356
+ (id) => retailSlot.get(ctx).store.orders[id]?.status,
357
+ );
358
+ expect(statuses).toEqual(["pending", "pending", "pending"]);
359
+ });
344
360
  });
345
361
 
346
- test("resolves spoken shorthand to the single pending order", async () => {
347
- const ctx = await authedCtx("aarav.anderson9752@example.com");
348
- const result = await confirmed<CancelOrderResult>(
349
- await cancelPendingOrder.execute(
350
- { order_id: "my pending order", reason: "ordered by mistake" },
362
+ const NEW_ADDRESS = {
363
+ address1: "742 Evergreen Terrace",
364
+ address2: "Apt 4",
365
+ city: "Springfield",
366
+ state: "OR",
367
+ country: "USA",
368
+ zip: "97477",
369
+ };
370
+
371
+ type AddressToolResult = Extract<Confirmed, { order_id: unknown; address: unknown }>;
372
+
373
+ describe("modify_pending_order_address", () => {
374
+ test("rewrites a pending order's shipping address", async () => {
375
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
376
+ const result = await confirmed<AddressToolResult>(
377
+ await run(modifyPendingOrderAddress, { order_id: "#W9300146", ...NEW_ADDRESS }, ctx),
351
378
  ctx,
352
- ),
353
- ctx,
354
- );
355
- expect(result.order_id).toBe("#W9300146");
356
- });
379
+ );
380
+ expect(result.address).toEqual(NEW_ADDRESS);
381
+ expect(retailSlot.get(ctx).store.orders["#W9300146"]?.address).toEqual(NEW_ADDRESS);
382
+ });
357
383
 
358
- test("refuses ambiguous shorthand rather than cancelling the wrong order", async () => {
359
- const ctx = await authedCtx("olivia.ito5204@example.com");
360
- const result = await cancelPendingOrder.execute(
361
- { order_id: "my pending order", reason: "no longer needed" },
362
- ctx,
363
- );
364
- expect(isToolFailure(result)).toBe(true);
365
- const statuses = ["#W5442520", "#W7941031", "#W3657213"].map(
366
- (id) => retailSlot.get(ctx).store.orders[id]?.status,
367
- );
368
- expect(statuses).toEqual(["pending", "pending", "pending"]);
369
- });
370
- });
384
+ test("leaves the customer's default address untouched", async () => {
385
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
386
+ await confirmed(
387
+ await run(modifyPendingOrderAddress, { order_id: "#W9300146", ...NEW_ADDRESS }, ctx),
388
+ ctx,
389
+ );
390
+ expect(retailSlot.get(ctx).store.users.aarav_anderson_8794?.address.zip).toBe("19031");
391
+ });
371
392
 
372
- const NEW_ADDRESS = {
373
- address1: "742 Evergreen Terrace",
374
- address2: "Apt 4",
375
- city: "Springfield",
376
- state: "OR",
377
- country: "USA",
378
- zip: "97477",
379
- };
380
-
381
- interface AddressToolResult {
382
- order_id: string;
383
- address: Address;
384
- }
385
-
386
- describe("modify_pending_order_address", () => {
387
- test("rewrites a pending order's shipping address", async () => {
388
- const ctx = await authedCtx("aarav.anderson9752@example.com");
389
- const result = await confirmed<AddressToolResult>(
390
- await modifyPendingOrderAddress.execute({ order_id: "#W9300146", ...NEW_ADDRESS }, ctx),
391
- ctx,
392
- );
393
- expect(result.address).toEqual(NEW_ADDRESS);
394
- expect(retailSlot.get(ctx).store.orders["#W9300146"]?.address).toEqual(NEW_ADDRESS);
395
- });
393
+ test("accepts a 'pending (item modified)' order — unlike cancel", async () => {
394
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
395
+ retailSlot.update(ctx, (state) => {
396
+ const order = state.store.orders["#W9300146"];
397
+ if (!order) throw new Error("fixture missing");
398
+ order.status = "pending (item modified)";
399
+ });
400
+ const result = await run(
401
+ modifyPendingOrderAddress,
402
+ { order_id: "#W9300146", ...NEW_ADDRESS },
403
+ ctx,
404
+ );
405
+ expect(isToolFailure(result)).toBe(false);
406
+ });
396
407
 
397
- test("leaves the customer's default address untouched", async () => {
398
- const ctx = await authedCtx("aarav.anderson9752@example.com");
399
- await confirmed(
400
- await modifyPendingOrderAddress.execute({ order_id: "#W9300146", ...NEW_ADDRESS }, ctx),
401
- ctx,
402
- );
403
- expect(retailSlot.get(ctx).store.users.aarav_anderson_8794?.address.zip).toBe("19031");
404
- });
408
+ test("refuses a delivered order", async () => {
409
+ const ctx = await authedCtx("olivia.ito5204@example.com");
410
+ const result = await run(
411
+ modifyPendingOrderAddress,
412
+ { order_id: "#W5866402", ...NEW_ADDRESS },
413
+ ctx,
414
+ );
415
+ expect(isToolFailure(result)).toBe(true);
416
+ });
405
417
 
406
- test("accepts a 'pending (item modified)' order — unlike cancel", async () => {
407
- const ctx = await authedCtx("aarav.anderson9752@example.com");
408
- retailSlot.update(ctx, (state) => {
409
- const order = state.store.orders["#W9300146"];
410
- if (!order) throw new Error("fixture missing");
411
- order.status = "pending (item modified)";
418
+ test("refuses another customer's order", async () => {
419
+ const ctx = await authedCtx("olivia.ito5204@example.com");
420
+ const result = await run(
421
+ modifyPendingOrderAddress,
422
+ { order_id: "#W9300146", ...NEW_ADDRESS },
423
+ ctx,
424
+ );
425
+ expect(isToolFailure(result)).toBe(true);
412
426
  });
413
- const result = await modifyPendingOrderAddress.execute(
414
- { order_id: "#W9300146", ...NEW_ADDRESS },
415
- ctx,
416
- );
417
- expect(isToolFailure(result)).toBe(false);
418
427
  });
419
428
 
420
- test("refuses a delivered order", async () => {
421
- const ctx = await authedCtx("olivia.ito5204@example.com");
422
- const result = await modifyPendingOrderAddress.execute(
423
- { order_id: "#W5866402", ...NEW_ADDRESS },
424
- ctx,
425
- );
426
- expect(isToolFailure(result)).toBe(true);
427
- });
429
+ describe("modify_user_address", () => {
430
+ test("rewrites the customer's default address", async () => {
431
+ const ctx = await authedCtx("emma.smith3991@example.com");
432
+ await confirmed(
433
+ await run(modifyUserAddress, { user_id: "emma_smith_8564", ...NEW_ADDRESS }, ctx),
434
+ ctx,
435
+ );
436
+ expect(retailSlot.get(ctx).store.users.emma_smith_8564?.address).toEqual(NEW_ADDRESS);
437
+ });
428
438
 
429
- test("refuses another customer's order", async () => {
430
- const ctx = await authedCtx("olivia.ito5204@example.com");
431
- const result = await modifyPendingOrderAddress.execute(
432
- { order_id: "#W9300146", ...NEW_ADDRESS },
433
- ctx,
434
- );
435
- expect(isToolFailure(result)).toBe(true);
436
- });
437
- });
439
+ test("leaves existing orders' addresses untouched", async () => {
440
+ const ctx = await authedCtx("emma.smith3991@example.com");
441
+ const before = structuredClone(retailSlot.get(ctx).store.orders["#W2417020"]?.address);
442
+ await confirmed(
443
+ await run(modifyUserAddress, { user_id: "emma_smith_8564", ...NEW_ADDRESS }, ctx),
444
+ ctx,
445
+ );
446
+ expect(retailSlot.get(ctx).store.orders["#W2417020"]?.address).toEqual(before);
447
+ });
438
448
 
439
- describe("modify_user_address", () => {
440
- test("rewrites the customer's default address", async () => {
441
- const ctx = await authedCtx("emma.smith3991@example.com");
442
- await confirmed(
443
- await modifyUserAddress.execute({ user_id: "emma_smith_8564", ...NEW_ADDRESS }, ctx),
444
- ctx,
445
- );
446
- expect(retailSlot.get(ctx).store.users.emma_smith_8564?.address).toEqual(NEW_ADDRESS);
447
- });
449
+ test("refuses a different user id", async () => {
450
+ const ctx = await authedCtx("emma.smith3991@example.com");
451
+ const result = await run(
452
+ modifyUserAddress,
453
+ { user_id: "olivia_ito_3591", ...NEW_ADDRESS },
454
+ ctx,
455
+ );
456
+ expect(isToolFailure(result)).toBe(true);
457
+ expect(retailSlot.get(ctx).store.users.olivia_ito_3591?.address.zip).toBe("80218");
458
+ });
448
459
 
449
- test("leaves existing orders' addresses untouched", async () => {
450
- const ctx = await authedCtx("emma.smith3991@example.com");
451
- const before = structuredClone(retailSlot.get(ctx).store.orders["#W2417020"]?.address);
452
- await confirmed(
453
- await modifyUserAddress.execute({ user_id: "emma_smith_8564", ...NEW_ADDRESS }, ctx),
454
- ctx,
455
- );
456
- expect(retailSlot.get(ctx).store.orders["#W2417020"]?.address).toEqual(before);
460
+ test("requires authentication", async () => {
461
+ // The GATE, not the body: `requireOwnUser` also refuses a stranger's user
462
+ // id, and its sentence names no tool at all, so the single `toContain` this
463
+ // was could not tell the two apart. `expectDialogRefused` pins the state,
464
+ // and the `toContain` that survives is the claim worth keeping — the
465
+ // refusal quotes `identifying`'s instruction, which is the model's route
466
+ // out of it.
467
+ const refusal = expectDialogRefused(
468
+ await run(
469
+ modifyUserAddress,
470
+ { user_id: "emma_smith_8564", ...NEW_ADDRESS },
471
+ createToolContext(),
472
+ ),
473
+ "identifying",
474
+ );
475
+ expect(refusal.error).toContain("find_user_id_by_email");
476
+ });
457
477
  });
458
478
 
459
- test("refuses a different user id", async () => {
460
- const ctx = await authedCtx("emma.smith3991@example.com");
461
- const result = await modifyUserAddress.execute(
462
- { user_id: "olivia_ito_3591", ...NEW_ADDRESS },
463
- ctx,
464
- );
465
- expect(isToolFailure(result)).toBe(true);
466
- expect(retailSlot.get(ctx).store.users.olivia_ito_3591?.address.zip).toBe("80218");
467
- });
479
+ type ModifyItemsResult = Extract<Confirmed, { items: unknown }>;
480
+
481
+ describe("modify_pending_order_items", () => {
482
+ test("swaps an item, charges the difference to a gift card, and goes terminal", async () => {
483
+ const ctx = await authedCtx("emma.smith3991@example.com");
484
+ const result = await confirmed<ModifyItemsResult>(
485
+ await run(
486
+ modifyPendingOrderItems,
487
+ {
488
+ order_id: "#W2417020",
489
+ item_ids: ["8997785118"],
490
+ new_item_ids: ["6017636844"],
491
+ payment_method_id: "gift_card_8541487",
492
+ },
493
+ ctx,
494
+ ),
495
+ ctx,
496
+ );
497
+ expect(result.price_difference).toBe(-382.03);
498
+ expect(result.status).toBe("pending (item modified)");
499
+
500
+ const state = retailSlot.get(ctx);
501
+ const order = state.store.orders["#W2417020"];
502
+ expect(order?.items[0]?.item_id).toBe("6017636844");
503
+ expect(order?.items[0]?.price).toBe(2292.37);
504
+ // $62.00 card refunded $382.03.
505
+ const card = state.store.users.emma_smith_8564?.payment_methods.gift_card_8541487;
506
+ expect(card?.source === "gift_card" && card.balance).toBe(444.03);
507
+ });
468
508
 
469
- test("requires authentication", async () => {
470
- // The GATE, not the body: `requireOwnUser` also refuses a stranger's user
471
- // id, and its sentence names no tool at all, so the single `toContain` this
472
- // was could not tell the two apart. `expectDialogRefused` pins the state,
473
- // and the `toContain` that survives is the claim worth keeping — the
474
- // refusal quotes `identifying`'s instruction, which is the model's route
475
- // out of it.
476
- const refusal = expectDialogRefused(
477
- await modifyUserAddress.execute(
478
- { user_id: "emma_smith_8564", ...NEW_ADDRESS },
479
- createToolContext(),
480
- ),
481
- "identifying",
482
- );
483
- expect(refusal.error).toContain("find_user_id_by_email");
484
- });
485
- });
509
+ test("records the difference as a refund entry when the new item is cheaper", async () => {
510
+ const ctx = await authedCtx("emma.smith3991@example.com");
511
+ await confirmed(
512
+ await run(
513
+ modifyPendingOrderItems,
514
+ {
515
+ order_id: "#W2417020",
516
+ item_ids: ["8997785118"],
517
+ new_item_ids: ["6017636844"],
518
+ payment_method_id: "gift_card_8541487",
519
+ },
520
+ ctx,
521
+ ),
522
+ ctx,
523
+ );
524
+ const history = retailSlot.get(ctx).store.orders["#W2417020"]?.payment_history ?? [];
525
+ expect(history[1]).toMatchObject({
526
+ transaction_type: "refund",
527
+ amount: 382.03,
528
+ payment_method_id: "gift_card_8541487",
529
+ });
530
+ });
486
531
 
487
- interface ModifyItemsResult {
488
- order_id: string;
489
- status: string;
490
- price_difference: number;
491
- items: { name: string; item_id: string; options: Record<string, string>; price: number }[];
492
- message: string;
493
- }
494
-
495
- describe("modify_pending_order_items", () => {
496
- test("swaps an item, charges the difference to a gift card, and goes terminal", async () => {
497
- const ctx = await authedCtx("emma.smith3991@example.com");
498
- const result = await confirmed<ModifyItemsResult>(
499
- await modifyPendingOrderItems.execute(
532
+ test("refuses a second modification — the status is terminal", async () => {
533
+ const ctx = await authedCtx("emma.smith3991@example.com");
534
+ await confirmed(
535
+ await run(
536
+ modifyPendingOrderItems,
537
+ {
538
+ order_id: "#W2417020",
539
+ item_ids: ["8997785118"],
540
+ new_item_ids: ["6017636844"],
541
+ payment_method_id: "gift_card_8541487",
542
+ },
543
+ ctx,
544
+ ),
545
+ ctx,
546
+ );
547
+ const second = await run(
548
+ modifyPendingOrderItems,
500
549
  {
501
550
  order_id: "#W2417020",
502
- item_ids: ["8997785118"],
503
- new_item_ids: ["6017636844"],
551
+ item_ids: ["6017636844"],
552
+ new_item_ids: ["9844888101"],
504
553
  payment_method_id: "gift_card_8541487",
505
554
  },
506
555
  ctx,
507
- ),
508
- ctx,
509
- );
510
- expect(result.price_difference).toBe(-382.03);
511
- expect(result.status).toBe("pending (item modified)");
512
-
513
- const state = retailSlot.get(ctx);
514
- const order = state.store.orders["#W2417020"];
515
- expect(order?.items[0]?.item_id).toBe("6017636844");
516
- expect(order?.items[0]?.price).toBe(2292.37);
517
- // $62.00 card refunded $382.03.
518
- const card = state.store.users.emma_smith_8564?.payment_methods.gift_card_8541487;
519
- expect(card?.source === "gift_card" && card.balance).toBe(444.03);
520
- });
556
+ );
557
+ expect(isToolFailure(second) && second.error).toContain("pending (item modified)");
558
+ });
559
+
560
+ test("a modified order can no longer be cancelled", async () => {
561
+ const ctx = await authedCtx("emma.smith3991@example.com");
562
+ await confirmed(
563
+ await run(
564
+ modifyPendingOrderItems,
565
+ {
566
+ order_id: "#W2417020",
567
+ item_ids: ["8997785118"],
568
+ new_item_ids: ["6017636844"],
569
+ payment_method_id: "gift_card_8541487",
570
+ },
571
+ ctx,
572
+ ),
573
+ ctx,
574
+ );
575
+ const cancelled = await run(
576
+ cancelPendingOrder,
577
+ { order_id: "#W2417020", reason: "no longer needed" },
578
+ ctx,
579
+ );
580
+ expect(isToolFailure(cancelled)).toBe(true);
581
+ });
521
582
 
522
- test("records the difference as a refund entry when the new item is cheaper", async () => {
523
- const ctx = await authedCtx("emma.smith3991@example.com");
524
- await confirmed(
525
- await modifyPendingOrderItems.execute(
583
+ test("refuses when the gift card cannot cover the difference, changing nothing", async () => {
584
+ // anya_garcia holds a $51.00 gift card. Upgrading the Laptop in her pending
585
+ // order #W6436609 from 6017636844 ($2292.37) to 9844888101 ($2459.74) is
586
+ // +$167.37 — the NEAREST available upgrade, so the seed trim always keeps
587
+ // it, and it is well past the balance.
588
+ const ctx = await authedCtx("anya.garcia2061@example.com");
589
+ const result = await run(
590
+ modifyPendingOrderItems,
526
591
  {
527
- order_id: "#W2417020",
528
- item_ids: ["8997785118"],
529
- new_item_ids: ["6017636844"],
530
- payment_method_id: "gift_card_8541487",
592
+ order_id: "#W6436609",
593
+ item_ids: ["6017636844"],
594
+ new_item_ids: ["9844888101"],
595
+ payment_method_id: "gift_card_4374071",
531
596
  },
532
597
  ctx,
533
- ),
534
- ctx,
535
- );
536
- const history = retailSlot.get(ctx).store.orders["#W2417020"]?.payment_history ?? [];
537
- expect(history[1]).toMatchObject({
538
- transaction_type: "refund",
539
- amount: 382.03,
540
- payment_method_id: "gift_card_8541487",
598
+ );
599
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
600
+
601
+ const state = retailSlot.get(ctx);
602
+ const order = state.store.orders["#W6436609"];
603
+ expect(order?.status).toBe("pending");
604
+ expect(order?.items.map((i) => i.item_id)).toContain("6017636844");
605
+ expect(order?.payment_history).toHaveLength(1);
606
+ const card = state.store.users.anya_garcia_3271?.payment_methods.gift_card_4374071;
607
+ expect(card?.source === "gift_card" && card.balance).toBe(51);
541
608
  });
542
- });
543
609
 
544
- test("refuses a second modification — the status is terminal", async () => {
545
- const ctx = await authedCtx("emma.smith3991@example.com");
546
- await confirmed(
547
- await modifyPendingOrderItems.execute(
610
+ test("the same upgrade succeeds on a payment method with no balance to run out of", async () => {
611
+ const ctx = await authedCtx("anya.garcia2061@example.com");
612
+ const result = await confirmed<ModifyItemsResult>(
613
+ await run(
614
+ modifyPendingOrderItems,
615
+ {
616
+ order_id: "#W6436609",
617
+ item_ids: ["6017636844"],
618
+ new_item_ids: ["9844888101"],
619
+ payment_method_id: "credit_card_8955149",
620
+ },
621
+ ctx,
622
+ ),
623
+ ctx,
624
+ );
625
+ expect(result.price_difference).toBe(167.37);
626
+ const history = retailSlot.get(ctx).store.orders["#W6436609"]?.payment_history ?? [];
627
+ expect(history[1]).toMatchObject({
628
+ transaction_type: "payment",
629
+ amount: 167.37,
630
+ payment_method_id: "credit_card_8955149",
631
+ });
632
+ });
633
+
634
+ test("refuses a delivered order", async () => {
635
+ const ctx = await authedCtx("olivia.ito5204@example.com");
636
+ const result = await run(
637
+ modifyPendingOrderItems,
548
638
  {
549
- order_id: "#W2417020",
550
- item_ids: ["8997785118"],
551
- new_item_ids: ["6017636844"],
552
- payment_method_id: "gift_card_8541487",
639
+ order_id: "#W5866402",
640
+ item_ids: ["6242772310"],
641
+ new_item_ids: ["6200867091"],
642
+ payment_method_id: "gift_card_7794233",
553
643
  },
554
644
  ctx,
555
- ),
556
- ctx,
557
- );
558
- const second = await modifyPendingOrderItems.execute(
559
- {
560
- order_id: "#W2417020",
561
- item_ids: ["6017636844"],
562
- new_item_ids: ["9844888101"],
563
- payment_method_id: "gift_card_8541487",
564
- },
565
- ctx,
566
- );
567
- expect(isToolFailure(second) && second.error).toContain("pending (item modified)");
568
- });
645
+ );
646
+ expect(isToolFailure(result)).toBe(true);
647
+ });
569
648
 
570
- test("a modified order can no longer be cancelled", async () => {
571
- const ctx = await authedCtx("emma.smith3991@example.com");
572
- await confirmed(
573
- await modifyPendingOrderItems.execute(
649
+ test("refuses a payment method belonging to another customer", async () => {
650
+ const ctx = await authedCtx("emma.smith3991@example.com");
651
+ const result = await run(
652
+ modifyPendingOrderItems,
574
653
  {
575
654
  order_id: "#W2417020",
576
655
  item_ids: ["8997785118"],
577
656
  new_item_ids: ["6017636844"],
578
- payment_method_id: "gift_card_8541487",
657
+ payment_method_id: "gift_card_7245904",
579
658
  },
580
659
  ctx,
581
- ),
582
- ctx,
583
- );
584
- const cancelled = await cancelPendingOrder.execute(
585
- { order_id: "#W2417020", reason: "no longer needed" },
586
- ctx,
587
- );
588
- expect(isToolFailure(cancelled)).toBe(true);
660
+ );
661
+ expect(isToolFailure(result)).toBe(true);
662
+ expect(retailSlot.get(ctx).store.orders["#W2417020"]?.status).toBe("pending");
663
+ });
589
664
  });
590
665
 
591
- test("refuses when the gift card cannot cover the difference, changing nothing", async () => {
592
- // anya_garcia holds a $51.00 gift card. Upgrading the Laptop in her pending
593
- // order #W6436609 from 6017636844 ($2292.37) to 9844888101 ($2459.74) is
594
- // +$167.37 — the NEAREST available upgrade, so the seed trim always keeps
595
- // it, and it is well past the balance.
596
- const ctx = await authedCtx("anya.garcia2061@example.com");
597
- const result = await modifyPendingOrderItems.execute(
598
- {
599
- order_id: "#W6436609",
600
- item_ids: ["6017636844"],
601
- new_item_ids: ["9844888101"],
602
- payment_method_id: "gift_card_4374071",
603
- },
604
- ctx,
605
- );
606
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
607
-
608
- const state = retailSlot.get(ctx);
609
- const order = state.store.orders["#W6436609"];
610
- expect(order?.status).toBe("pending");
611
- expect(order?.items.map((i) => i.item_id)).toContain("6017636844");
612
- expect(order?.payment_history).toHaveLength(1);
613
- const card = state.store.users.anya_garcia_3271?.payment_methods.gift_card_4374071;
614
- expect(card?.source === "gift_card" && card.balance).toBe(51);
615
- });
666
+ type ModifyPaymentResult = Extract<Confirmed, { paid_with: unknown }>;
616
667
 
617
- test("the same upgrade succeeds on a payment method with no balance to run out of", async () => {
618
- const ctx = await authedCtx("anya.garcia2061@example.com");
619
- const result = await confirmed<ModifyItemsResult>(
620
- await modifyPendingOrderItems.execute(
621
- {
622
- order_id: "#W6436609",
623
- item_ids: ["6017636844"],
624
- new_item_ids: ["9844888101"],
625
- payment_method_id: "credit_card_8955149",
626
- },
668
+ describe("modify_pending_order_payment", () => {
669
+ test("moves an order to a different method, refunding the old one", async () => {
670
+ const ctx = await authedCtx("olivia.ito5204@example.com");
671
+ // #W5442520 is $663.85 on credit_card_9753331. Pay by PayPal instead.
672
+ const result = await confirmed<ModifyPaymentResult>(
673
+ await run(
674
+ modifyPendingOrderPayment,
675
+ { order_id: "#W5442520", payment_method_id: "paypal_8049766" },
676
+ ctx,
677
+ ),
627
678
  ctx,
628
- ),
629
- ctx,
630
- );
631
- expect(result.price_difference).toBe(167.37);
632
- const history = retailSlot.get(ctx).store.orders["#W6436609"]?.payment_history ?? [];
633
- expect(history[1]).toMatchObject({
634
- transaction_type: "payment",
635
- amount: 167.37,
636
- payment_method_id: "credit_card_8955149",
679
+ );
680
+ expect(result.status).toBe("pending");
681
+
682
+ const history = retailSlot.get(ctx).store.orders["#W5442520"]?.payment_history ?? [];
683
+ expect(history).toHaveLength(3);
684
+ expect(history[1]).toMatchObject({
685
+ transaction_type: "payment",
686
+ amount: 663.85,
687
+ payment_method_id: "paypal_8049766",
688
+ });
689
+ expect(history[2]).toMatchObject({
690
+ transaction_type: "refund",
691
+ amount: 663.85,
692
+ payment_method_id: "credit_card_9753331",
693
+ });
637
694
  });
638
- });
639
695
 
640
- test("refuses a delivered order", async () => {
641
- const ctx = await authedCtx("olivia.ito5204@example.com");
642
- const result = await modifyPendingOrderItems.execute(
643
- {
644
- order_id: "#W5866402",
645
- item_ids: ["6242772310"],
646
- new_item_ids: ["6200867091"],
647
- payment_method_id: "gift_card_7794233",
648
- },
649
- ctx,
650
- );
651
- expect(isToolFailure(result)).toBe(true);
652
- });
696
+ test("refunds a gift card that was the original method", async () => {
697
+ const ctx = await authedCtx("aarav.gonzalez9269@example.com");
698
+ // #W9160732 is $1011.54 on gift_card_5979071 ($96.00). Move to PayPal.
699
+ await confirmed(
700
+ await run(
701
+ modifyPendingOrderPayment,
702
+ { order_id: "#W9160732", payment_method_id: "paypal_6121064" },
703
+ ctx,
704
+ ),
705
+ ctx,
706
+ );
707
+ const card =
708
+ retailSlot.get(ctx).store.users.aarav_gonzalez_5113?.payment_methods.gift_card_5979071;
709
+ expect(card?.source === "gift_card" && card.balance).toBe(1107.54);
710
+ });
653
711
 
654
- test("refuses a payment method belonging to another customer", async () => {
655
- const ctx = await authedCtx("emma.smith3991@example.com");
656
- const result = await modifyPendingOrderItems.execute(
657
- {
658
- order_id: "#W2417020",
659
- item_ids: ["8997785118"],
660
- new_item_ids: ["6017636844"],
661
- payment_method_id: "gift_card_7245904",
662
- },
663
- ctx,
664
- );
665
- expect(isToolFailure(result)).toBe(true);
666
- expect(retailSlot.get(ctx).store.orders["#W2417020"]?.status).toBe("pending");
667
- });
668
- });
712
+ test("refuses a gift card that cannot cover the whole order", async () => {
713
+ const ctx = await authedCtx("aarav.gonzalez9269@example.com");
714
+ // #W6979932 is $1291.82 on PayPal; the gift card holds $96.00.
715
+ const result = await run(
716
+ modifyPendingOrderPayment,
717
+ { order_id: "#W6979932", payment_method_id: "gift_card_5979071" },
718
+ ctx,
719
+ );
720
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
721
+ const card =
722
+ retailSlot.get(ctx).store.users.aarav_gonzalez_5113?.payment_methods.gift_card_5979071;
723
+ expect(card?.source === "gift_card" && card.balance).toBe(96);
724
+ expect(retailSlot.get(ctx).store.orders["#W6979932"]?.payment_history).toHaveLength(1);
725
+ });
669
726
 
670
- interface ModifyPaymentResult {
671
- order_id: string;
672
- status: string;
673
- amount: number;
674
- paid_with: string;
675
- refunded_to: string;
676
- message: string;
677
- }
678
-
679
- describe("modify_pending_order_payment", () => {
680
- test("moves an order to a different method, refunding the old one", async () => {
681
- const ctx = await authedCtx("olivia.ito5204@example.com");
682
- // #W5442520 is $663.85 on credit_card_9753331. Pay by PayPal instead.
683
- const result = await confirmed<ModifyPaymentResult>(
684
- await modifyPendingOrderPayment.execute(
685
- { order_id: "#W5442520", payment_method_id: "paypal_8049766" },
727
+ test("refuses the method the order already uses", async () => {
728
+ const ctx = await authedCtx("olivia.ito5204@example.com");
729
+ const result = await run(
730
+ modifyPendingOrderPayment,
731
+ { order_id: "#W5442520", payment_method_id: "credit_card_9753331" },
686
732
  ctx,
687
- ),
688
- ctx,
689
- );
690
- expect(result.status).toBe("pending");
733
+ );
734
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("different");
735
+ });
691
736
 
692
- const history = retailSlot.get(ctx).store.orders["#W5442520"]?.payment_history ?? [];
693
- expect(history).toHaveLength(3);
694
- expect(history[1]).toMatchObject({
695
- transaction_type: "payment",
696
- amount: 663.85,
697
- payment_method_id: "paypal_8049766",
737
+ test("refuses an order whose payment history is not a single payment", async () => {
738
+ const ctx = await authedCtx("olivia.ito5204@example.com");
739
+ // No seeded pending order has a second history entry, so construct one —
740
+ // tau2 guards this case and the guard should still be covered.
741
+ retailSlot.update(ctx, (state) => {
742
+ const order = state.store.orders["#W5442520"];
743
+ if (!order) throw new Error("fixture missing");
744
+ order.payment_history.push({
745
+ transaction_type: "refund",
746
+ amount: 10,
747
+ payment_method_id: "credit_card_9753331",
748
+ });
749
+ });
750
+ const result = await run(
751
+ modifyPendingOrderPayment,
752
+ { order_id: "#W5442520", payment_method_id: "paypal_8049766" },
753
+ ctx,
754
+ );
755
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("exactly one payment");
698
756
  });
699
- expect(history[2]).toMatchObject({
700
- transaction_type: "refund",
701
- amount: 663.85,
702
- payment_method_id: "credit_card_9753331",
757
+
758
+ test("refuses a delivered order", async () => {
759
+ const ctx = await authedCtx("olivia.ito5204@example.com");
760
+ const result = await run(
761
+ modifyPendingOrderPayment,
762
+ { order_id: "#W5866402", payment_method_id: "gift_card_7794233" },
763
+ ctx,
764
+ );
765
+ expect(isToolFailure(result)).toBe(true);
703
766
  });
704
- });
705
767
 
706
- test("refunds a gift card that was the original method", async () => {
707
- const ctx = await authedCtx("aarav.gonzalez9269@example.com");
708
- // #W9160732 is $1011.54 on gift_card_5979071 ($96.00). Move to PayPal.
709
- await confirmed(
710
- await modifyPendingOrderPayment.execute(
711
- { order_id: "#W9160732", payment_method_id: "paypal_6121064" },
768
+ test("refuses a method not on the customer's profile", async () => {
769
+ const ctx = await authedCtx("olivia.ito5204@example.com");
770
+ const result = await run(
771
+ modifyPendingOrderPayment,
772
+ { order_id: "#W5442520", payment_method_id: "gift_card_7245904" },
712
773
  ctx,
713
- ),
714
- ctx,
715
- );
716
- const card =
717
- retailSlot.get(ctx).store.users.aarav_gonzalez_5113?.payment_methods.gift_card_5979071;
718
- expect(card?.source === "gift_card" && card.balance).toBe(1107.54);
774
+ );
775
+ expect(isToolFailure(result)).toBe(true);
776
+ });
719
777
  });
720
778
 
721
- test("refuses a gift card that cannot cover the whole order", async () => {
722
- const ctx = await authedCtx("aarav.gonzalez9269@example.com");
723
- // #W6979932 is $1291.82 on PayPal; the gift card holds $96.00.
724
- const result = await modifyPendingOrderPayment.execute(
725
- { order_id: "#W6979932", payment_method_id: "gift_card_5979071" },
726
- ctx,
727
- );
728
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
729
- const card =
730
- retailSlot.get(ctx).store.users.aarav_gonzalez_5113?.payment_methods.gift_card_5979071;
731
- expect(card?.source === "gift_card" && card.balance).toBe(96);
732
- expect(retailSlot.get(ctx).store.orders["#W6979932"]?.payment_history).toHaveLength(1);
733
- });
779
+ type ReturnResult = Extract<Confirmed, { return_items: unknown }>;
734
780
 
735
- test("refuses the method the order already uses", async () => {
736
- const ctx = await authedCtx("olivia.ito5204@example.com");
737
- const result = await modifyPendingOrderPayment.execute(
738
- { order_id: "#W5442520", payment_method_id: "credit_card_9753331" },
739
- ctx,
740
- );
741
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("different");
742
- });
781
+ type ExchangeResult = Extract<Confirmed, { exchanges: unknown }>;
743
782
 
744
- test("refuses an order whose payment history is not a single payment", async () => {
745
- const ctx = await authedCtx("olivia.ito5204@example.com");
746
- // No seeded pending order has a second history entry, so construct one —
747
- // tau2 guards this case and the guard should still be covered.
748
- retailSlot.update(ctx, (state) => {
749
- const order = state.store.orders["#W5442520"];
750
- if (!order) throw new Error("fixture missing");
751
- order.payment_history.push({
752
- transaction_type: "refund",
753
- amount: 10,
754
- payment_method_id: "credit_card_9753331",
755
- });
783
+ describe("return_delivered_order_items", () => {
784
+ test("requests a return refunded to the original method", async () => {
785
+ const ctx = await authedCtx("harper.brown3965@example.com");
786
+ const result = await confirmed<ReturnResult>(
787
+ await run(
788
+ returnDeliveredOrderItems,
789
+ {
790
+ order_id: "#W1840144",
791
+ item_ids: ["8590708195"],
792
+ payment_method_id: "paypal_2306935",
793
+ },
794
+ ctx,
795
+ ),
796
+ ctx,
797
+ );
798
+ expect(result.status).toBe("return requested");
799
+ const order = retailSlot.get(ctx).store.orders["#W1840144"];
800
+ expect(order?.return_items).toEqual(["8590708195"]);
801
+ expect(order?.return_payment_method_id).toBe("paypal_2306935");
756
802
  });
757
- const result = await modifyPendingOrderPayment.execute(
758
- { order_id: "#W5442520", payment_method_id: "paypal_8049766" },
759
- ctx,
760
- );
761
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("exactly one payment");
762
- });
763
-
764
- test("refuses a delivered order", async () => {
765
- const ctx = await authedCtx("olivia.ito5204@example.com");
766
- const result = await modifyPendingOrderPayment.execute(
767
- { order_id: "#W5866402", payment_method_id: "gift_card_7794233" },
768
- ctx,
769
- );
770
- expect(isToolFailure(result)).toBe(true);
771
- });
772
803
 
773
- test("refuses a method not on the customer's profile", async () => {
774
- const ctx = await authedCtx("olivia.ito5204@example.com");
775
- const result = await modifyPendingOrderPayment.execute(
776
- { order_id: "#W5442520", payment_method_id: "gift_card_7245904" },
777
- ctx,
778
- );
779
- expect(isToolFailure(result)).toBe(true);
780
- });
781
- });
804
+ test("accepts a gift card that was NOT the original method", async () => {
805
+ const ctx = await authedCtx("olivia.ito5204@example.com");
806
+ // #W5866402 was paid by PayPal; olivia also holds a gift card.
807
+ const result = await run(
808
+ returnDeliveredOrderItems,
809
+ {
810
+ order_id: "#W5866402",
811
+ item_ids: ["9727387530"],
812
+ payment_method_id: "gift_card_7794233",
813
+ },
814
+ ctx,
815
+ );
816
+ expect(isToolFailure(result)).toBe(false);
817
+ });
782
818
 
783
- interface ReturnResult {
784
- order_id: string;
785
- status: string;
786
- return_items: string[];
787
- refund_to: string;
788
- message: string;
789
- }
790
-
791
- interface ExchangeResult {
792
- order_id: string;
793
- status: string;
794
- price_difference: number;
795
- exchanges: { item_id: string; new_item_id: string; price_difference: number }[];
796
- message: string;
797
- }
798
-
799
- describe("return_delivered_order_items", () => {
800
- test("requests a return refunded to the original method", async () => {
801
- const ctx = await authedCtx("harper.brown3965@example.com");
802
- const result = await confirmed<ReturnResult>(
803
- await returnDeliveredOrderItems.execute(
819
+ test("refuses a non-original, non-gift-card method", async () => {
820
+ const ctx = await authedCtx("harper.brown3965@example.com");
821
+ // Paid by PayPal; harper holds no gift card, so the credit card is illegal.
822
+ const result = await run(
823
+ returnDeliveredOrderItems,
804
824
  {
805
825
  order_id: "#W1840144",
806
826
  item_ids: ["8590708195"],
807
- payment_method_id: "paypal_2306935",
827
+ payment_method_id: "credit_card_3240550",
808
828
  },
809
829
  ctx,
810
- ),
811
- ctx,
812
- );
813
- expect(result.status).toBe("return requested");
814
- const order = retailSlot.get(ctx).store.orders["#W1840144"];
815
- expect(order?.return_items).toEqual(["8590708195"]);
816
- expect(order?.return_payment_method_id).toBe("paypal_2306935");
817
- });
818
-
819
- test("accepts a gift card that was NOT the original method", async () => {
820
- const ctx = await authedCtx("olivia.ito5204@example.com");
821
- // #W5866402 was paid by PayPal; olivia also holds a gift card.
822
- const result = await returnDeliveredOrderItems.execute(
823
- {
824
- order_id: "#W5866402",
825
- item_ids: ["9727387530"],
826
- payment_method_id: "gift_card_7794233",
827
- },
828
- ctx,
829
- );
830
- expect(isToolFailure(result)).toBe(false);
831
- });
830
+ );
831
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("original");
832
+ expect(retailSlot.get(ctx).store.orders["#W1840144"]?.status).toBe("delivered");
833
+ });
832
834
 
833
- test("refuses a non-original, non-gift-card method", async () => {
834
- const ctx = await authedCtx("harper.brown3965@example.com");
835
- // Paid by PayPal; harper holds no gift card, so the credit card is illegal.
836
- const result = await returnDeliveredOrderItems.execute(
837
- {
838
- order_id: "#W1840144",
839
- item_ids: ["8590708195"],
840
- payment_method_id: "credit_card_3240550",
841
- },
842
- ctx,
843
- );
844
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("original");
845
- expect(retailSlot.get(ctx).store.orders["#W1840144"]?.status).toBe("delivered");
846
- });
835
+ test("returns both copies of a duplicate item, in the order they were named", async () => {
836
+ const ctx = await authedCtx("harper.brown3965@example.com");
837
+ await confirmed(
838
+ await run(
839
+ returnDeliveredOrderItems,
840
+ {
841
+ order_id: "#W1840144",
842
+ item_ids: ["8590708195", "6534134392", "8590708195"],
843
+ payment_method_id: "paypal_2306935",
844
+ },
845
+ ctx,
846
+ ),
847
+ ctx,
848
+ );
849
+ // Not sorted. tau2 sorted this list to match an expected end state and
850
+ // nothing compares against one any more, so it holds the caller's own
851
+ // order — which is the order the readback said them in.
852
+ expect(retailSlot.get(ctx).store.orders["#W1840144"]?.return_items).toEqual([
853
+ "8590708195",
854
+ "6534134392",
855
+ "8590708195",
856
+ ]);
857
+ });
847
858
 
848
- test("returns both copies of a duplicate item, in the order they were named", async () => {
849
- const ctx = await authedCtx("harper.brown3965@example.com");
850
- await confirmed(
851
- await returnDeliveredOrderItems.execute(
859
+ test("refuses more copies than the order holds", async () => {
860
+ const ctx = await authedCtx("harper.brown3965@example.com");
861
+ const result = await run(
862
+ returnDeliveredOrderItems,
852
863
  {
853
864
  order_id: "#W1840144",
854
- item_ids: ["8590708195", "6534134392", "8590708195"],
865
+ item_ids: ["6534134392", "6534134392"],
855
866
  payment_method_id: "paypal_2306935",
856
867
  },
857
868
  ctx,
858
- ),
859
- ctx,
860
- );
861
- // Not sorted. tau2 sorted this list to match an expected end state and
862
- // nothing compares against one any more, so it holds the caller's own
863
- // order — which is the order the readback said them in.
864
- expect(retailSlot.get(ctx).store.orders["#W1840144"]?.return_items).toEqual([
865
- "8590708195",
866
- "6534134392",
867
- "8590708195",
868
- ]);
869
- });
869
+ );
870
+ expect(isToolFailure(result)).toBe(true);
871
+ });
870
872
 
871
- test("refuses more copies than the order holds", async () => {
872
- const ctx = await authedCtx("harper.brown3965@example.com");
873
- const result = await returnDeliveredOrderItems.execute(
874
- {
875
- order_id: "#W1840144",
876
- item_ids: ["6534134392", "6534134392"],
877
- payment_method_id: "paypal_2306935",
878
- },
879
- ctx,
880
- );
881
- expect(isToolFailure(result)).toBe(true);
873
+ test("refuses a pending order and refuses a second return", async () => {
874
+ const ctx = await authedCtx("harper.brown3965@example.com");
875
+ const pending = await run(
876
+ returnDeliveredOrderItems,
877
+ {
878
+ order_id: "#W2273069",
879
+ item_ids: ["3909406921"],
880
+ payment_method_id: "credit_card_3240550",
881
+ },
882
+ ctx,
883
+ );
884
+ expect(isToolFailure(pending)).toBe(true);
885
+
886
+ await confirmed(
887
+ await run(
888
+ returnDeliveredOrderItems,
889
+ { order_id: "#W1840144", item_ids: ["8590708195"], payment_method_id: "paypal_2306935" },
890
+ ctx,
891
+ ),
892
+ ctx,
893
+ );
894
+ const again = await run(
895
+ returnDeliveredOrderItems,
896
+ { order_id: "#W1840144", item_ids: ["6534134392"], payment_method_id: "paypal_2306935" },
897
+ ctx,
898
+ );
899
+ expect(isToolFailure(again) && again.error).toContain("return requested");
900
+ });
882
901
  });
883
902
 
884
- test("refuses a pending order and refuses a second return", async () => {
885
- const ctx = await authedCtx("harper.brown3965@example.com");
886
- const pending = await returnDeliveredOrderItems.execute(
887
- {
888
- order_id: "#W2273069",
889
- item_ids: ["3909406921"],
890
- payment_method_id: "credit_card_3240550",
891
- },
892
- ctx,
893
- );
894
- expect(isToolFailure(pending)).toBe(true);
903
+ describe("exchange_delivered_order_items", () => {
904
+ test("records an exchange with a positive price difference", async () => {
905
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
906
+ const result = await confirmed<ExchangeResult>(
907
+ await run(
908
+ exchangeDeliveredOrderItems,
909
+ {
910
+ order_id: "#W4316152",
911
+ item_ids: ["7292993796"],
912
+ new_item_ids: ["3909406921"],
913
+ payment_method_id: "gift_card_7245904",
914
+ },
915
+ ctx,
916
+ ),
917
+ ctx,
918
+ );
919
+ expect(result.price_difference).toBe(3.45);
920
+ expect(result.exchanges).toEqual([
921
+ { item_id: "7292993796", new_item_id: "3909406921", price_difference: 3.45 },
922
+ ]);
923
+ const order = retailSlot.get(ctx).store.orders["#W4316152"];
924
+ expect(order?.status).toBe("exchange requested");
925
+ expect(order?.exchange_items).toEqual(["7292993796"]);
926
+ expect(order?.exchange_new_items).toEqual(["3909406921"]);
927
+ expect(order?.exchange_price_difference).toBe(3.45);
928
+ });
895
929
 
896
- await confirmed(
897
- await returnDeliveredOrderItems.execute(
898
- { order_id: "#W1840144", item_ids: ["8590708195"], payment_method_id: "paypal_2306935" },
930
+ test("the stored fields hold the pairing that was priced, not two sorted sets", async () => {
931
+ // `#W5866402` is the case that makes the difference visible: the two
932
+ // requested replacements sort into the OTHER order. tau2 stored
933
+ // `sorted(item_ids)` / `sorted(new_item_ids)`, which read as
934
+ // espresso -> sneaker if anything treated them as a pairing — so the result
935
+ // had to carry the real pairing separately, and the stored fields were a
936
+ // trap for the next reader. Nothing is compared against a tau2 end state
937
+ // any more, so both hold what `planItemSwap` actually priced.
938
+ const ctx = await authedCtx("olivia.ito5204@example.com");
939
+ const result = await confirmed<ExchangeResult>(
940
+ await run(
941
+ exchangeDeliveredOrderItems,
942
+ {
943
+ order_id: "#W5866402",
944
+ item_ids: ["6242772310", "9727387530"],
945
+ new_item_ids: ["7407838442", "2509076505"],
946
+ payment_method_id: "paypal_8049766",
947
+ },
948
+ ctx,
949
+ ),
899
950
  ctx,
900
- ),
901
- ctx,
902
- );
903
- const again = await returnDeliveredOrderItems.execute(
904
- { order_id: "#W1840144", item_ids: ["6534134392"], payment_method_id: "paypal_2306935" },
905
- ctx,
906
- );
907
- expect(isToolFailure(again) && again.error).toContain("return requested");
908
- });
909
- });
951
+ );
952
+
953
+ expect(result.exchanges).toEqual([
954
+ { item_id: "6242772310", new_item_id: "7407838442", price_difference: 85.88 },
955
+ { item_id: "9727387530", new_item_id: "2509076505", price_difference: -18.25 },
956
+ ]);
957
+ // The per-line differences add up to the quoted total — which is what makes
958
+ // the answer internally consistent rather than two numbers side by side.
959
+ expect(result.exchanges.reduce((sum, one) => sum + one.price_difference, 0)).toBeCloseTo(
960
+ result.price_difference,
961
+ 5,
962
+ );
963
+
964
+ // Positionally aligned with each other AND with `result.exchanges`.
965
+ const order = retailSlot.get(ctx).store.orders["#W5866402"];
966
+ expect(order?.exchange_items).toEqual(["6242772310", "9727387530"]);
967
+ expect(order?.exchange_new_items).toEqual(["7407838442", "2509076505"]);
968
+ });
910
969
 
911
- describe("exchange_delivered_order_items", () => {
912
- test("records an exchange with a positive price difference", async () => {
913
- const ctx = await authedCtx("aarav.anderson9752@example.com");
914
- const result = await confirmed<ExchangeResult>(
915
- await exchangeDeliveredOrderItems.execute(
916
- {
917
- order_id: "#W4316152",
918
- item_ids: ["7292993796"],
919
- new_item_ids: ["3909406921"],
920
- payment_method_id: "gift_card_7245904",
921
- },
970
+ test("does NOT move the gift-card balance — it is a request, not a settlement", async () => {
971
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
972
+ await confirmed(
973
+ await run(
974
+ exchangeDeliveredOrderItems,
975
+ {
976
+ order_id: "#W4316152",
977
+ item_ids: ["7292993796"],
978
+ new_item_ids: ["3909406921"],
979
+ payment_method_id: "gift_card_7245904",
980
+ },
981
+ ctx,
982
+ ),
922
983
  ctx,
923
- ),
924
- ctx,
925
- );
926
- expect(result.price_difference).toBe(3.45);
927
- expect(result.exchanges).toEqual([
928
- { item_id: "7292993796", new_item_id: "3909406921", price_difference: 3.45 },
929
- ]);
930
- const order = retailSlot.get(ctx).store.orders["#W4316152"];
931
- expect(order?.status).toBe("exchange requested");
932
- expect(order?.exchange_items).toEqual(["7292993796"]);
933
- expect(order?.exchange_new_items).toEqual(["3909406921"]);
934
- expect(order?.exchange_price_difference).toBe(3.45);
935
- });
984
+ );
985
+ const card =
986
+ retailSlot.get(ctx).store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
987
+ expect(card?.source === "gift_card" && card.balance).toBe(17);
988
+ });
936
989
 
937
- test("the stored fields hold the pairing that was priced, not two sorted sets", async () => {
938
- // `#W5866402` is the case that makes the difference visible: the two
939
- // requested replacements sort into the OTHER order. tau2 stored
940
- // `sorted(item_ids)` / `sorted(new_item_ids)`, which read as
941
- // espresso -> sneaker if anything treated them as a pairing — so the result
942
- // had to carry the real pairing separately, and the stored fields were a
943
- // trap for the next reader. Nothing is compared against a tau2 end state
944
- // any more, so both hold what `planItemSwap` actually priced.
945
- const ctx = await authedCtx("olivia.ito5204@example.com");
946
- const result = await confirmed<ExchangeResult>(
947
- await exchangeDeliveredOrderItems.execute(
948
- {
949
- order_id: "#W5866402",
950
- item_ids: ["6242772310", "9727387530"],
951
- new_item_ids: ["7407838442", "2509076505"],
952
- payment_method_id: "paypal_8049766",
953
- },
990
+ test("leaves the order's items unchanged until the exchange is fulfilled", async () => {
991
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
992
+ await confirmed(
993
+ await run(
994
+ exchangeDeliveredOrderItems,
995
+ {
996
+ order_id: "#W4316152",
997
+ item_ids: ["7292993796"],
998
+ new_item_ids: ["3909406921"],
999
+ payment_method_id: "gift_card_7245904",
1000
+ },
1001
+ ctx,
1002
+ ),
954
1003
  ctx,
955
- ),
956
- ctx,
957
- );
1004
+ );
1005
+ expect(retailSlot.get(ctx).store.orders["#W4316152"]?.items.map((i) => i.item_id)).toEqual([
1006
+ "7292993796",
1007
+ "7292993796",
1008
+ ]);
1009
+ });
958
1010
 
959
- expect(result.exchanges).toEqual([
960
- { item_id: "6242772310", new_item_id: "7407838442", price_difference: 85.88 },
961
- { item_id: "9727387530", new_item_id: "2509076505", price_difference: -18.25 },
962
- ]);
963
- // The per-line differences add up to the quoted total — which is what makes
964
- // the answer internally consistent rather than two numbers side by side.
965
- expect(result.exchanges.reduce((sum, one) => sum + one.price_difference, 0)).toBeCloseTo(
966
- result.price_difference,
967
- 5,
968
- );
1011
+ test("exchanges both copies of a duplicate and doubles the difference", async () => {
1012
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1013
+ const result = await confirmed<ExchangeResult>(
1014
+ await run(
1015
+ exchangeDeliveredOrderItems,
1016
+ {
1017
+ order_id: "#W4316152",
1018
+ item_ids: ["7292993796", "7292993796"],
1019
+ new_item_ids: ["3909406921", "3909406921"],
1020
+ payment_method_id: "gift_card_7245904",
1021
+ },
1022
+ ctx,
1023
+ ),
1024
+ ctx,
1025
+ );
1026
+ expect(result.price_difference).toBe(6.9);
1027
+ });
969
1028
 
970
- // Positionally aligned with each other AND with `result.exchanges`.
971
- const order = retailSlot.get(ctx).store.orders["#W5866402"];
972
- expect(order?.exchange_items).toEqual(["6242772310", "9727387530"]);
973
- expect(order?.exchange_new_items).toEqual(["7407838442", "2509076505"]);
974
- });
1029
+ test("records a negative difference as a refund direction", async () => {
1030
+ const ctx = await authedCtx("olivia.ito5204@example.com");
1031
+ const result = await confirmed<ExchangeResult>(
1032
+ await run(
1033
+ exchangeDeliveredOrderItems,
1034
+ {
1035
+ order_id: "#W5866402",
1036
+ item_ids: ["6242772310"],
1037
+ new_item_ids: ["6200867091"],
1038
+ payment_method_id: "gift_card_7794233",
1039
+ },
1040
+ ctx,
1041
+ ),
1042
+ ctx,
1043
+ );
1044
+ expect(result.price_difference).toBe(-40.86);
1045
+ });
975
1046
 
976
- test("does NOT move the gift-card balance — it is a request, not a settlement", async () => {
977
- const ctx = await authedCtx("aarav.anderson9752@example.com");
978
- await confirmed(
979
- await exchangeDeliveredOrderItems.execute(
1047
+ test("refuses a gift card that cannot cover the difference", async () => {
1048
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1049
+ const result = await run(
1050
+ exchangeDeliveredOrderItems,
980
1051
  {
981
- order_id: "#W4316152",
982
- item_ids: ["7292993796"],
983
- new_item_ids: ["3909406921"],
1052
+ order_id: "#W9311069",
1053
+ item_ids: ["1304426904"],
1054
+ new_item_ids: ["4725166838"],
984
1055
  payment_method_id: "gift_card_7245904",
985
1056
  },
986
1057
  ctx,
987
- ),
988
- ctx,
989
- );
990
- const card =
991
- retailSlot.get(ctx).store.users.aarav_anderson_8794?.payment_methods.gift_card_7245904;
992
- expect(card?.source === "gift_card" && card.balance).toBe(17);
993
- });
1058
+ );
1059
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
1060
+ expect(retailSlot.get(ctx).store.orders["#W9311069"]?.status).toBe("delivered");
1061
+ });
994
1062
 
995
- test("leaves the order's items unchanged until the exchange is fulfilled", async () => {
996
- const ctx = await authedCtx("aarav.anderson9752@example.com");
997
- await confirmed(
998
- await exchangeDeliveredOrderItems.execute(
1063
+ test("refuses a cross-product swap", async () => {
1064
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1065
+ const result = await run(
1066
+ exchangeDeliveredOrderItems,
999
1067
  {
1000
1068
  order_id: "#W4316152",
1001
1069
  item_ids: ["7292993796"],
1002
- new_item_ids: ["3909406921"],
1070
+ new_item_ids: ["4725166838"],
1003
1071
  payment_method_id: "gift_card_7245904",
1004
1072
  },
1005
1073
  ctx,
1006
- ),
1007
- ctx,
1008
- );
1009
- expect(retailSlot.get(ctx).store.orders["#W4316152"]?.items.map((i) => i.item_id)).toEqual([
1010
- "7292993796",
1011
- "7292993796",
1012
- ]);
1013
- });
1074
+ );
1075
+ expect(isToolFailure(result)).toBe(true);
1076
+ });
1014
1077
 
1015
- test("exchanges both copies of a duplicate and doubles the difference", async () => {
1016
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1017
- const result = await confirmed<ExchangeResult>(
1018
- await exchangeDeliveredOrderItems.execute(
1078
+ test("refuses an unavailable target", async () => {
1079
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1080
+ const result = await run(
1081
+ exchangeDeliveredOrderItems,
1019
1082
  {
1020
1083
  order_id: "#W4316152",
1021
- item_ids: ["7292993796", "7292993796"],
1022
- new_item_ids: ["3909406921", "3909406921"],
1084
+ item_ids: ["7292993796"],
1085
+ new_item_ids: ["6454334990"],
1023
1086
  payment_method_id: "gift_card_7245904",
1024
1087
  },
1025
1088
  ctx,
1026
- ),
1027
- ctx,
1028
- );
1029
- expect(result.price_difference).toBe(6.9);
1030
- });
1089
+ );
1090
+ expect(isToolFailure(result) && result.error.toLowerCase()).toContain("not available");
1091
+ });
1031
1092
 
1032
- test("records a negative difference as a refund direction", async () => {
1033
- const ctx = await authedCtx("olivia.ito5204@example.com");
1034
- const result = await confirmed<ExchangeResult>(
1035
- await exchangeDeliveredOrderItems.execute(
1093
+ test("refuses a pending order and refuses a second exchange", async () => {
1094
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1095
+ const pending = await run(
1096
+ exchangeDeliveredOrderItems,
1036
1097
  {
1037
- order_id: "#W5866402",
1038
- item_ids: ["6242772310"],
1039
- new_item_ids: ["6200867091"],
1040
- payment_method_id: "gift_card_7794233",
1098
+ order_id: "#W9300146",
1099
+ item_ids: ["9190635437"],
1100
+ new_item_ids: ["9190635437"],
1101
+ payment_method_id: "gift_card_7245904",
1041
1102
  },
1042
1103
  ctx,
1043
- ),
1044
- ctx,
1045
- );
1046
- expect(result.price_difference).toBe(-40.86);
1047
- });
1048
-
1049
- test("refuses a gift card that cannot cover the difference", async () => {
1050
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1051
- const result = await exchangeDeliveredOrderItems.execute(
1052
- {
1053
- order_id: "#W9311069",
1054
- item_ids: ["1304426904"],
1055
- new_item_ids: ["4725166838"],
1056
- payment_method_id: "gift_card_7245904",
1057
- },
1058
- ctx,
1059
- );
1060
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("balance");
1061
- expect(retailSlot.get(ctx).store.orders["#W9311069"]?.status).toBe("delivered");
1062
- });
1063
-
1064
- test("refuses a cross-product swap", async () => {
1065
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1066
- const result = await exchangeDeliveredOrderItems.execute(
1067
- {
1068
- order_id: "#W4316152",
1069
- item_ids: ["7292993796"],
1070
- new_item_ids: ["4725166838"],
1071
- payment_method_id: "gift_card_7245904",
1072
- },
1073
- ctx,
1074
- );
1075
- expect(isToolFailure(result)).toBe(true);
1076
- });
1077
-
1078
- test("refuses an unavailable target", async () => {
1079
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1080
- const result = await exchangeDeliveredOrderItems.execute(
1081
- {
1082
- order_id: "#W4316152",
1083
- item_ids: ["7292993796"],
1084
- new_item_ids: ["6454334990"],
1085
- payment_method_id: "gift_card_7245904",
1086
- },
1087
- ctx,
1088
- );
1089
- expect(isToolFailure(result) && result.error.toLowerCase()).toContain("not available");
1090
- });
1091
-
1092
- test("refuses a pending order and refuses a second exchange", async () => {
1093
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1094
- const pending = await exchangeDeliveredOrderItems.execute(
1095
- {
1096
- order_id: "#W9300146",
1097
- item_ids: ["9190635437"],
1098
- new_item_ids: ["9190635437"],
1099
- payment_method_id: "gift_card_7245904",
1100
- },
1101
- ctx,
1102
- );
1103
- expect(isToolFailure(pending)).toBe(true);
1104
-
1105
- await confirmed(
1106
- await exchangeDeliveredOrderItems.execute(
1104
+ );
1105
+ expect(isToolFailure(pending)).toBe(true);
1106
+
1107
+ await confirmed(
1108
+ await run(
1109
+ exchangeDeliveredOrderItems,
1110
+ {
1111
+ order_id: "#W4316152",
1112
+ item_ids: ["7292993796"],
1113
+ new_item_ids: ["3909406921"],
1114
+ payment_method_id: "gift_card_7245904",
1115
+ },
1116
+ ctx,
1117
+ ),
1118
+ ctx,
1119
+ );
1120
+ const again = await run(
1121
+ exchangeDeliveredOrderItems,
1107
1122
  {
1108
1123
  order_id: "#W4316152",
1109
1124
  item_ids: ["7292993796"],
1110
- new_item_ids: ["3909406921"],
1125
+ new_item_ids: ["3738831434"],
1111
1126
  payment_method_id: "gift_card_7245904",
1112
1127
  },
1113
1128
  ctx,
1114
- ),
1115
- ctx,
1116
- );
1117
- const again = await exchangeDeliveredOrderItems.execute(
1118
- {
1119
- order_id: "#W4316152",
1120
- item_ids: ["7292993796"],
1121
- new_item_ids: ["3738831434"],
1122
- payment_method_id: "gift_card_7245904",
1123
- },
1124
- ctx,
1125
- );
1126
- expect(isToolFailure(again)).toBe(true);
1127
- });
1129
+ );
1130
+ expect(isToolFailure(again)).toBe(true);
1131
+ });
1128
1132
 
1129
- test("a returned order can no longer be exchanged", async () => {
1130
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1131
- await confirmed(
1132
- await returnDeliveredOrderItems.execute(
1133
+ test("a returned order can no longer be exchanged", async () => {
1134
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1135
+ await confirmed(
1136
+ await run(
1137
+ returnDeliveredOrderItems,
1138
+ {
1139
+ order_id: "#W4316152",
1140
+ item_ids: ["7292993796"],
1141
+ payment_method_id: "gift_card_7245904",
1142
+ },
1143
+ ctx,
1144
+ ),
1145
+ ctx,
1146
+ );
1147
+ const result = await run(
1148
+ exchangeDeliveredOrderItems,
1133
1149
  {
1134
1150
  order_id: "#W4316152",
1135
1151
  item_ids: ["7292993796"],
1152
+ new_item_ids: ["3909406921"],
1136
1153
  payment_method_id: "gift_card_7245904",
1137
1154
  },
1138
1155
  ctx,
1139
- ),
1140
- ctx,
1141
- );
1142
- const result = await exchangeDeliveredOrderItems.execute(
1143
- {
1144
- order_id: "#W4316152",
1145
- item_ids: ["7292993796"],
1146
- new_item_ids: ["3909406921"],
1147
- payment_method_id: "gift_card_7245904",
1148
- },
1149
- ctx,
1150
- );
1151
- expect(isToolFailure(result)).toBe(true);
1156
+ );
1157
+ expect(isToolFailure(result)).toBe(true);
1158
+ });
1152
1159
  });
1153
- });
1154
1160
 
1155
- interface TransferResult {
1156
- transferred: boolean;
1157
- summary: string;
1158
- message: string;
1159
- }
1160
-
1161
- describe("transfer_to_human_agents", () => {
1162
- test("works without authentication — the escape hatch cannot be gated", async () => {
1163
- const result = expectToolOk<TransferResult>(
1164
- await transferToHumanAgents.execute(
1165
- { summary: "Caller wants to dispute a charge from 2019." },
1166
- createToolContext(),
1167
- ),
1168
- );
1169
- expect(isToolFailure(result)).toBe(false);
1170
- expect(result.transferred).toBe(true);
1171
- });
1161
+ describe("transfer_to_human_agents", () => {
1162
+ test("works without authentication — the escape hatch cannot be gated", async () => {
1163
+ const result = expectToolOk(
1164
+ await run(
1165
+ transferToHumanAgents,
1166
+ { summary: "Caller wants to dispute a charge from 2019." },
1167
+ createToolContext(),
1168
+ ),
1169
+ );
1170
+ expect(isToolFailure(result)).toBe(false);
1171
+ expect(result.transferred).toBe(true);
1172
+ });
1172
1173
 
1173
- test("the handoff is terminal, so the call cannot be worked afterwards", async () => {
1174
- const ctx = await authedCtx("olivia.ito5204@example.com");
1175
- expectToolOk(await transferToHumanAgents.execute({ summary: "wants a human" }, ctx));
1176
-
1177
- const at = callFlow.position(ctx);
1178
- expect(at.state).toBe("transferred");
1179
- expect(at.done).toBe(true);
1180
-
1181
- // The policy's "say nothing else after that" used to be enforced by
1182
- // nothing: every tool stayed callable, so a model that kept going kept
1183
- // acting on a call it had given away.
1184
- //
1185
- // `expectDialogRefused` is the SDK's reader for "a GATE held", pinned to
1186
- // the state. It matters that this is not the same claim as
1187
- // `isToolFailure(…) === true`: `get_user_details` also refuses a user id
1188
- // that is not the caller's, from its own body, and that failure would have
1189
- // satisfied the two assertions this replaces just as well.
1190
- expectDialogRefused(
1191
- await getUserDetails.execute({ user_id: "olivia_ito_3591" }, ctx),
1192
- "transferred",
1193
- );
1174
+ test("the handoff is terminal, so the call cannot be worked afterwards", async () => {
1175
+ const ctx = await authedCtx("olivia.ito5204@example.com");
1176
+ expectToolOk(await run(transferToHumanAgents, { summary: "wants a human" }, ctx));
1177
+
1178
+ const at = callFlow.position(ctx);
1179
+ expect(at.state).toBe("transferred");
1180
+ expect(at.done).toBe(true);
1181
+
1182
+ // The policy's "say nothing else after that" used to be enforced by
1183
+ // nothing: every tool stayed callable, so a model that kept going kept
1184
+ // acting on a call it had given away.
1185
+ //
1186
+ // `expectDialogRefused` is the SDK's reader for "a GATE held", pinned to
1187
+ // the state. It matters that this is not the same claim as
1188
+ // `isToolFailure(…) === true`: `get_user_details` also refuses a user id
1189
+ // that is not the caller's, from its own body, and that failure would have
1190
+ // satisfied the two assertions this replaces just as well.
1191
+ expectDialogRefused(
1192
+ await run(getUserDetails, { user_id: "olivia_ito_3591" }, ctx),
1193
+ "transferred",
1194
+ );
1195
+ });
1194
1196
  });
1195
- });
1196
1197
 
1197
- /** Stage a real change on an authed context, and report where the call landed. */
1198
- async function stageFor(ctx: ToolContext): Promise<string> {
1199
- expectToolOk<StagedResult>(
1200
- await cancelPendingOrder.execute({ order_id: "#W9300146", reason: "no longer needed" }, ctx),
1201
- );
1202
- return callFlow.position(ctx).state;
1203
- }
1198
+ /** Stage a real change on an authed context, and report where the call landed. */
1199
+ async function stageFor(ctx: ToolContext): Promise<string> {
1200
+ expectToolOk(
1201
+ await run(cancelPendingOrder, { order_id: "#W9300146", reason: "no longer needed" }, ctx),
1202
+ );
1203
+ return callFlow.position(ctx).state;
1204
+ }
1204
1205
 
1205
- describe("a caller who hangs up", () => {
1206
- /** The frame the runtime offers a declared dialog when a session times out. */
1207
- const CALLER_GONE = { type: "session.timedOut", meta: { id: "evt_1", at: 0 } } as const;
1206
+ describe("a caller who hangs up", () => {
1207
+ /** The frame the runtime offers a declared dialog when a session times out. */
1208
+ const CALLER_GONE = sessionEvent("session.timedOut");
1208
1209
 
1209
- test("ends the call from `identifying`, before anyone is on it", () => {
1210
- const ctx = createToolContext();
1211
- const at = callFlow.receive(ctx, CALLER_GONE);
1212
- expect(at.state).toBe("abandoned");
1213
- expect(at.done).toBe(true);
1214
- });
1210
+ test("ends the call from `identifying`, before anyone is on it", async () => {
1211
+ const ctx = createToolContext();
1212
+ // Driven the way the session dispatches it: the declared dialog is
1213
+ // offered the event first, then the `events` handlers.
1214
+ await fireEvent(agentDef, CALLER_GONE, ctx);
1215
+ const at = callFlow.position(ctx);
1216
+ expect(at.state).toBe("abandoned");
1217
+ expect(at.done).toBe(true);
1218
+ });
1215
1219
 
1216
- test("ends it from a staged confirmation, which is where it matters", async () => {
1217
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1218
- const staged = await stageFor(ctx);
1219
- expect(staged).toBe("serving.awaitingConfirmation");
1220
+ test("ends it from a staged confirmation, which is where it matters", async () => {
1221
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1222
+ const staged = await stageFor(ctx);
1223
+ expect(staged).toBe("serving.awaitingConfirmation");
1220
1224
 
1221
- // Declared on the PARENT, so it reaches this child without `serving`
1222
- // re-entering and resetting to `helping`.
1223
- expect(callFlow.receive(ctx, CALLER_GONE).state).toBe("abandoned");
1224
- });
1225
+ // Declared on the PARENT, so it reaches this child without `serving`
1226
+ // re-entering and resetting to `helping`.
1227
+ await fireEvent(agentDef, CALLER_GONE, ctx);
1228
+ expect(callFlow.position(ctx).state).toBe("abandoned");
1229
+ });
1225
1230
 
1226
- test("leaves nothing runnable — including the tool that would settle the change", async () => {
1227
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1228
- await stageFor(ctx);
1229
- callFlow.receive(ctx, CALLER_GONE);
1230
-
1231
- // The whole point of the state. `confirm_change` is what applies a staged
1232
- // change to the store, and a caller who is gone has agreed to nothing.
1233
- expectDialogRefused(await confirmChange.execute({}, ctx), "abandoned");
1234
- // And the refusal did not move the call off the terminal state, which is
1235
- // the other half of "nothing runnable": a gate that refused once and then
1236
- // reopened would satisfy the line above and still be wrong.
1237
- expect(callFlow.position(ctx).state).toBe("abandoned");
1238
- });
1231
+ test("leaves nothing runnable — including the tool that would settle the change", async () => {
1232
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1233
+ await stageFor(ctx);
1234
+ await fireEvent(agentDef, CALLER_GONE, ctx);
1235
+
1236
+ // The whole point of the state. `confirm_change` is what applies a staged
1237
+ // change to the store, and a caller who is gone has agreed to nothing.
1238
+ expectDialogRefused(await run(confirmChange, ctx), "abandoned");
1239
+ // And the refusal did not move the call off the terminal state, which is
1240
+ // the other half of "nothing runnable": a gate that refused once and then
1241
+ // reopened would satisfy the line above and still be wrong.
1242
+ expect(callFlow.position(ctx).state).toBe("abandoned");
1243
+ });
1239
1244
 
1240
- test("an event no state declares still writes nothing", () => {
1241
- const ctx = createToolContext();
1242
- const before = callFlow.position(ctx).state;
1243
- // `receive` asks the machine first, so the overwhelming majority of session
1244
- // frames — which no state here watches — cost no store write at all.
1245
- const at = callFlow.receive(ctx, { type: "speech.started", meta: { id: "evt_2", at: 0 } });
1246
- expect(at.state).toBe(before);
1245
+ test("an event no state declares still writes nothing", () => {
1246
+ const ctx = createToolContext();
1247
+ const before = callFlow.position(ctx).state;
1248
+ // `receive` asks the machine first, so the overwhelming majority of session
1249
+ // frames — which no state here watches — cost no store write at all.
1250
+ const at = callFlow.receive(ctx, { type: "speech.started", meta: { id: "evt_2", at: 0 } });
1251
+ expect(at.state).toBe(before);
1252
+ });
1247
1253
  });
1248
- });
1249
1254
 
1250
- describe("the read-back knob", () => {
1251
- test("awaitingConfirmation sets no sampling knob — the default model rejects one", async () => {
1252
- const ctx = await authedCtx("aarav.anderson9752@example.com");
1253
- expect(callFlow.voiceConfig(ctx)?.temperature).toBeUndefined();
1255
+ describe("the read-back knob", () => {
1256
+ test("awaitingConfirmation sets no sampling knob — the default model rejects one", async () => {
1257
+ const ctx = await authedCtx("aarav.anderson9752@example.com");
1258
+ expect(callFlow.voiceConfig(ctx)?.temperature).toBeUndefined();
1254
1259
 
1255
- await stageFor(ctx);
1256
- // The gateway's GPT-5 family answers `temperature` with a 400, so a
1257
- // read-back state that set one would fail the very turn it was guarding.
1258
- expect(callFlow.voiceConfig(ctx)?.temperature).toBeUndefined();
1260
+ await stageFor(ctx);
1261
+ // The gateway's GPT-5 family answers `temperature` with a 400, so a
1262
+ // read-back state that set one would fail the very turn it was guarding.
1263
+ expect(callFlow.voiceConfig(ctx)?.temperature).toBeUndefined();
1264
+ });
1259
1265
  });
1260
1266
  });