@alexkroman1/aai-cli 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (438) 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-D6VSQbYW.mjs → _dev-server-C_zidzWj.mjs} +15 -10
  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-tVBjfKyR.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-CT_QHHZL.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 +44 -34
  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/document-redline-workflow/agent.test.ts +88 -221
  102. package/dist/templates/document-redline-workflow/agent.ts +22 -32
  103. package/dist/templates/document-redline-workflow/client.tsx +46 -88
  104. package/dist/templates/document-redline-workflow/workflows/prompts.ts +0 -3
  105. package/dist/templates/document-redline-workflow/workflows/redline.ts +33 -50
  106. package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +22 -71
  107. package/dist/templates/emergency-dispatch-agent/agent.test.ts +466 -495
  108. package/dist/templates/emergency-dispatch-agent/agent.ts +27 -43
  109. package/dist/templates/emergency-dispatch-agent/client.tsx +85 -119
  110. package/dist/templates/emergency-dispatch-agent/shared.ts +51 -88
  111. package/dist/templates/emergency-dispatch-agent/tools/incident_add_note.ts +11 -17
  112. package/dist/templates/emergency-dispatch-agent/tools/incident_create.ts +21 -30
  113. package/dist/templates/emergency-dispatch-agent/tools/incident_escalate.ts +60 -63
  114. package/dist/templates/emergency-dispatch-agent/tools/incident_get.ts +6 -15
  115. package/dist/templates/emergency-dispatch-agent/tools/incident_triage.ts +40 -53
  116. package/dist/templates/emergency-dispatch-agent/tools/incident_update_status.ts +41 -47
  117. package/dist/templates/emergency-dispatch-agent/tools/ops_dashboard.ts +2 -2
  118. package/dist/templates/emergency-dispatch-agent/tools/ops_protocols.ts +1 -1
  119. package/dist/templates/emergency-dispatch-agent/tools/ops_run_scenario.ts +13 -10
  120. package/dist/templates/emergency-dispatch-agent/tools/resources_dispatch.ts +42 -51
  121. package/dist/templates/emergency-dispatch-agent/tools/resources_update_status.ts +40 -41
  122. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +14 -42
  123. package/dist/templates/entertainment-picks-agent/agent.test.ts +174 -221
  124. package/dist/templates/entertainment-picks-agent/agent.ts +1 -6
  125. package/dist/templates/entertainment-picks-agent/client.tsx +1 -12
  126. package/dist/templates/entertainment-picks-agent/shared.ts +12 -6
  127. package/dist/templates/entertainment-picks-agent/tools/recommend.ts +2 -2
  128. package/dist/templates/entertainment-picks-agent/tools/revisit.ts +1 -0
  129. package/dist/templates/executive-inbox-agent/agent.eval.test.ts +15 -22
  130. package/dist/templates/executive-inbox-agent/agent.test.ts +515 -527
  131. package/dist/templates/executive-inbox-agent/agent.ts +4 -8
  132. package/dist/templates/executive-inbox-agent/calendar.test.ts +23 -22
  133. package/dist/templates/executive-inbox-agent/client.tsx +1 -23
  134. package/dist/templates/executive-inbox-agent/review.ts +125 -113
  135. package/dist/templates/executive-inbox-agent/shared.ts +3 -0
  136. package/dist/templates/executive-inbox-agent/tools/ask_question.ts +6 -6
  137. package/dist/templates/executive-inbox-agent/tools/draft_reply.ts +16 -18
  138. package/dist/templates/executive-inbox-agent/tools/inbox_status.ts +1 -0
  139. package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +20 -20
  140. package/dist/templates/executive-inbox-agent/tools/new_email.ts +17 -21
  141. package/dist/templates/executive-inbox-agent/tools/open_email.ts +72 -74
  142. package/dist/templates/executive-inbox-agent/tools/review_memory.ts +1 -0
  143. package/dist/templates/executive-inbox-agent/tools/send_calendar_invite.ts +19 -20
  144. package/dist/templates/executive-inbox-agent/tools/triage_inbox.ts +53 -50
  145. package/dist/templates/front-desk-agent/agent.eval.test.ts +22 -14
  146. package/dist/templates/front-desk-agent/agent.test.ts +139 -123
  147. package/dist/templates/front-desk-agent/agent.ts +4 -7
  148. package/dist/templates/front-desk-agent/shared.ts +88 -74
  149. package/dist/templates/front-door-agent/agent.eval.test.ts +61 -0
  150. package/dist/templates/front-door-agent/agent.test.ts +393 -0
  151. package/dist/templates/front-door-agent/agent.ts +35 -0
  152. package/dist/templates/front-door-agent/client.tsx +250 -0
  153. package/dist/templates/front-door-agent/routes.ts +91 -0
  154. package/dist/templates/front-door-agent/shared.ts +35 -0
  155. package/dist/templates/front-door-agent/system-prompt.md +12 -0
  156. package/dist/templates/front-door-agent/tools/leave_message.ts +39 -0
  157. package/dist/templates/front-door-agent/tools/link_phone.ts +49 -0
  158. package/dist/templates/front-door-agent/workflows/announce.ts +38 -0
  159. package/dist/templates/front-door-agent/workflows/digest.ts +53 -0
  160. package/dist/templates/front-door-agent/workflows/pair.ts +28 -0
  161. package/dist/templates/home-assistant-agent/agent.eval.test.ts +5 -9
  162. package/dist/templates/home-assistant-agent/agent.test.ts +513 -399
  163. package/dist/templates/home-assistant-agent/agent.ts +8 -5
  164. package/dist/templates/home-assistant-agent/client.tsx +48 -9
  165. package/dist/templates/home-assistant-agent/tools/cancel_reminders.ts +1 -0
  166. package/dist/templates/home-assistant-agent/tools/remind_me.ts +2 -1
  167. package/dist/templates/hotel-reception-agent/agent.eval.test.ts +27 -52
  168. package/dist/templates/hotel-reception-agent/agent.test.ts +980 -964
  169. package/dist/templates/hotel-reception-agent/agent.ts +8 -21
  170. package/dist/templates/hotel-reception-agent/booking.ts +2 -2
  171. package/dist/templates/hotel-reception-agent/client.tsx +5 -20
  172. package/dist/templates/hotel-reception-agent/concierge.ts +2 -0
  173. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +285 -275
  174. package/dist/templates/hotel-reception-agent/desk.ts +45 -12
  175. package/dist/templates/hotel-reception-agent/hotel.ts +6 -6
  176. package/dist/templates/hotel-reception-agent/restaurant.ts +3 -4
  177. package/dist/templates/hotel-reception-agent/session.ts +14 -30
  178. package/dist/templates/hotel-reception-agent/shared.ts +33 -46
  179. package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +14 -15
  180. package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +1 -0
  181. package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +1 -0
  182. package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +2 -2
  183. package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +13 -10
  184. package/dist/templates/hotel-reception-agent/tools/choose_room.ts +1 -1
  185. package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +6 -7
  186. package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +1 -0
  187. package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +5 -4
  188. package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +6 -5
  189. package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +3 -4
  190. package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +4 -4
  191. package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +1 -0
  192. package/dist/templates/hotel-reception-agent/tools/record_card.ts +1 -1
  193. package/dist/templates/hotel-reception-agent/tools/record_followup.ts +1 -0
  194. package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +1 -0
  195. package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +1 -1
  196. package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +1 -0
  197. package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +1 -0
  198. package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +4 -4
  199. package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +1 -0
  200. package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +4 -3
  201. package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +1 -0
  202. package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +1 -0
  203. package/dist/templates/hotel-reception-agent/tools/set_extras.ts +1 -1
  204. package/dist/templates/hotel-reception-agent/tools/set_stay.ts +1 -1
  205. package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +30 -32
  206. package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +22 -25
  207. package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +1 -0
  208. package/dist/templates/hotel-reception-agent/tools/update_card.ts +5 -4
  209. package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +23 -13
  210. package/dist/templates/kitchen-coach-agent/agent.eval.test.ts +38 -0
  211. package/dist/templates/kitchen-coach-agent/agent.test.ts +204 -0
  212. package/dist/templates/kitchen-coach-agent/agent.ts +22 -0
  213. package/dist/templates/kitchen-coach-agent/client.tsx +232 -0
  214. package/dist/templates/kitchen-coach-agent/history.ts +37 -0
  215. package/dist/templates/kitchen-coach-agent/shared.ts +131 -0
  216. package/dist/templates/kitchen-coach-agent/system-prompt.md +17 -0
  217. package/dist/templates/kitchen-coach-agent/tools/get_kitchen.ts +17 -0
  218. package/dist/templates/kitchen-coach-agent/tools/scale_amount.ts +31 -0
  219. package/dist/templates/kitchen-coach-agent/tools/start_timer.ts +24 -0
  220. package/dist/templates/link-digest-workflow/agent.eval.test.ts +16 -40
  221. package/dist/templates/link-digest-workflow/agent.test.ts +84 -164
  222. package/dist/templates/link-digest-workflow/agent.ts +27 -42
  223. package/dist/templates/link-digest-workflow/api-client.ts +3 -2
  224. package/dist/templates/link-digest-workflow/client.tsx +5 -5
  225. package/dist/templates/link-digest-workflow/workflows/digest.ts +53 -95
  226. package/dist/templates/medication-safety-agent/agent.eval.test.ts +10 -30
  227. package/dist/templates/medication-safety-agent/agent.test.ts +16 -46
  228. package/dist/templates/medication-safety-agent/agent.ts +1 -4
  229. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +13 -10
  230. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +238 -396
  231. package/dist/templates/meeting-recap-agent/agent.test.ts +414 -1070
  232. package/dist/templates/meeting-recap-agent/agent.ts +26 -67
  233. package/dist/templates/meeting-recap-agent/system-prompt.md +1 -0
  234. package/dist/templates/meeting-recap-agent/tools/keep_transcript.ts +10 -12
  235. package/dist/templates/meeting-recap-agent/tools/request_recap.ts +9 -20
  236. package/dist/templates/meeting-recap-agent/workflows/recap.ts +224 -547
  237. package/dist/templates/outbound-call-agent/agent.eval.test.ts +10 -12
  238. package/dist/templates/outbound-call-agent/agent.test.ts +419 -453
  239. package/dist/templates/outbound-call-agent/agent.ts +57 -62
  240. package/dist/templates/outbound-call-agent/api.ts +53 -68
  241. package/dist/templates/outbound-call-agent/client.tsx +105 -176
  242. package/dist/templates/outbound-call-agent/shared.ts +10 -39
  243. package/dist/templates/outbound-call-agent/system-prompt.md +3 -4
  244. package/dist/templates/outbound-call-agent/tools/end_call.ts +15 -12
  245. package/dist/templates/outbound-call-agent/tools/press_keys.ts +8 -13
  246. package/dist/templates/outbound-call-agent/workflows/call.ts +89 -62
  247. package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +18 -54
  248. package/dist/templates/pizza-ordering-agent/agent.test.ts +205 -244
  249. package/dist/templates/pizza-ordering-agent/agent.ts +5 -12
  250. package/dist/templates/pizza-ordering-agent/client.tsx +3 -14
  251. package/dist/templates/pizza-ordering-agent/shared.ts +31 -36
  252. package/dist/templates/pizza-ordering-agent/tools/add_pizza.ts +1 -0
  253. package/dist/templates/pizza-ordering-agent/tools/place_order.ts +5 -2
  254. package/dist/templates/pizza-ordering-agent/tools/remove_pizza.ts +1 -0
  255. package/dist/templates/pizza-ordering-agent/tools/update_pizza.ts +2 -3
  256. package/dist/templates/pizza-ordering-agent/tools/view_order.ts +7 -3
  257. package/dist/templates/podcast-digest-workflow/agent.test.ts +53 -102
  258. package/dist/templates/podcast-digest-workflow/agent.ts +11 -17
  259. package/dist/templates/podcast-digest-workflow/client.tsx +29 -51
  260. package/dist/templates/podcast-digest-workflow/workflows/digest.ts +24 -26
  261. package/dist/templates/push-to-talk-agent/agent.eval.test.ts +13 -14
  262. package/dist/templates/push-to-talk-agent/agent.test.ts +30 -23
  263. package/dist/templates/push-to-talk-agent/agent.ts +1 -5
  264. package/dist/templates/push-to-talk-agent/client.tsx +1 -11
  265. package/dist/templates/push-to-talk-agent/shared.ts +12 -6
  266. package/dist/templates/push-to-talk-agent/tools/list_notes.ts +1 -0
  267. package/dist/templates/push-to-talk-agent/tools/save_note.ts +1 -0
  268. package/dist/templates/quickstart-agent/agent.eval.test.ts +0 -10
  269. package/dist/templates/quickstart-agent/agent.test.ts +18 -30
  270. package/dist/templates/quickstart-agent/agent.ts +3 -4
  271. package/dist/templates/research-handoff-agent/agent.eval.test.ts +161 -290
  272. package/dist/templates/research-handoff-agent/agent.test.ts +131 -457
  273. package/dist/templates/research-handoff-agent/agent.ts +26 -86
  274. package/dist/templates/research-handoff-agent/system-prompt.md +1 -0
  275. package/dist/templates/research-handoff-agent/tools/file_it_now.ts +8 -21
  276. package/dist/templates/research-handoff-agent/tools/request_research.ts +7 -16
  277. package/dist/templates/research-handoff-agent/workflows/research.ts +88 -40
  278. package/dist/templates/research-planner-agent/agent.eval.test.ts +15 -40
  279. package/dist/templates/research-planner-agent/agent.test.ts +415 -464
  280. package/dist/templates/research-planner-agent/agent.ts +3 -8
  281. package/dist/templates/research-planner-agent/client.tsx +1 -14
  282. package/dist/templates/research-planner-agent/procedure.ts +9 -3
  283. package/dist/templates/research-planner-agent/shared.ts +30 -33
  284. package/dist/templates/research-planner-agent/tools/plan_status.ts +7 -15
  285. package/dist/templates/research-planner-agent/tools/revise_plan.ts +29 -36
  286. package/dist/templates/research-planner-agent/tools/start_plan.ts +25 -39
  287. package/dist/templates/research-planner-agent/tools/work_next_step.ts +25 -42
  288. package/dist/templates/retail-orders-agent/agent.eval.test.ts +14 -34
  289. package/dist/templates/retail-orders-agent/agent.test.ts +1079 -1073
  290. package/dist/templates/retail-orders-agent/agent.ts +25 -78
  291. package/dist/templates/retail-orders-agent/client.tsx +120 -168
  292. package/dist/templates/retail-orders-agent/pending.test.ts +7 -14
  293. package/dist/templates/retail-orders-agent/registry.test.ts +93 -192
  294. package/dist/templates/retail-orders-agent/shared.test.ts +1 -1
  295. package/dist/templates/retail-orders-agent/shared.ts +10 -20
  296. package/dist/templates/retail-orders-agent/store.test.ts +46 -128
  297. package/dist/templates/retail-orders-agent/store.ts +42 -175
  298. package/dist/templates/retail-orders-agent/tools/cancel_change.ts +3 -6
  299. package/dist/templates/retail-orders-agent/tools/cancel_pending_order.ts +3 -4
  300. package/dist/templates/retail-orders-agent/tools/confirm_change.ts +4 -6
  301. package/dist/templates/retail-orders-agent/tools/exchange_delivered_order_items.ts +3 -4
  302. package/dist/templates/retail-orders-agent/tools/find_user_id_by_email.ts +3 -4
  303. package/dist/templates/retail-orders-agent/tools/find_user_id_by_name_zip.ts +3 -4
  304. package/dist/templates/retail-orders-agent/tools/get_item_details.ts +3 -4
  305. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +3 -4
  306. package/dist/templates/retail-orders-agent/tools/get_product_details.ts +3 -4
  307. package/dist/templates/retail-orders-agent/tools/get_user_details.ts +3 -4
  308. package/dist/templates/retail-orders-agent/tools/list_all_product_types.ts +3 -8
  309. package/dist/templates/retail-orders-agent/tools/modify_pending_order_address.ts +3 -4
  310. package/dist/templates/retail-orders-agent/tools/modify_pending_order_items.ts +3 -4
  311. package/dist/templates/retail-orders-agent/tools/modify_pending_order_payment.ts +3 -4
  312. package/dist/templates/retail-orders-agent/tools/modify_user_address.ts +3 -4
  313. package/dist/templates/retail-orders-agent/tools/return_delivered_order_items.ts +3 -4
  314. package/dist/templates/retail-orders-agent/tools/transfer_to_human_agents.ts +3 -4
  315. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +22 -25
  316. package/dist/templates/roadside-assistance-agent/agent.test.ts +453 -490
  317. package/dist/templates/roadside-assistance-agent/agent.ts +28 -60
  318. package/dist/templates/roadside-assistance-agent/call.ts +16 -22
  319. package/dist/templates/roadside-assistance-agent/shared.ts +24 -54
  320. package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +29 -37
  321. package/dist/templates/roadside-assistance-agent/tools/dispatch_truck.ts +44 -70
  322. package/dist/templates/roadside-assistance-agent/tools/job_status.ts +16 -24
  323. package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +39 -51
  324. package/dist/templates/roadside-assistance-agent/tools/report_location.ts +34 -33
  325. package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +18 -39
  326. package/dist/templates/roadside-assistance-agent/yard.test.ts +22 -19
  327. package/dist/templates/roadside-assistance-agent/yard.ts +3 -3
  328. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +38 -40
  329. package/dist/templates/spoken-summary-workflow/agent.test.ts +129 -279
  330. package/dist/templates/spoken-summary-workflow/agent.ts +15 -40
  331. package/dist/templates/spoken-summary-workflow/client.tsx +13 -25
  332. package/dist/templates/spoken-summary-workflow/workflows/summarize.ts +52 -92
  333. package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +31 -74
  334. package/dist/templates/tabletop-rpg-agent/agent.test.ts +756 -774
  335. package/dist/templates/tabletop-rpg-agent/agent.ts +9 -46
  336. package/dist/templates/tabletop-rpg-agent/client.tsx +13 -21
  337. package/dist/templates/tabletop-rpg-agent/shared.ts +40 -99
  338. package/dist/templates/tabletop-rpg-agent/tools/action_roll.ts +67 -83
  339. package/dist/templates/tabletop-rpg-agent/tools/burn_momentum.ts +65 -88
  340. package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +8 -27
  341. package/dist/templates/tabletop-rpg-agent/tools/setup_character.ts +18 -36
  342. package/dist/templates/tabletop-rpg-agent/tools/update_state.ts +101 -111
  343. package/dist/templates/technical-support-agent/agent.eval.test.ts +31 -72
  344. package/dist/templates/technical-support-agent/agent.test.ts +231 -260
  345. package/dist/templates/technical-support-agent/agent.ts +4 -10
  346. package/dist/templates/technical-support-agent/client.tsx +4 -18
  347. package/dist/templates/technical-support-agent/shared.ts +15 -25
  348. package/dist/templates/technical-support-agent/tools/answer_question.ts +46 -56
  349. package/dist/templates/technical-support-agent/tools/list_topics.ts +1 -0
  350. package/dist/templates/technical-support-agent/tools/log_ticket.ts +8 -5
  351. package/dist/templates/text-adventure-agent/agent.eval.test.ts +37 -126
  352. package/dist/templates/text-adventure-agent/agent.test.ts +197 -368
  353. package/dist/templates/text-adventure-agent/agent.ts +15 -65
  354. package/dist/templates/text-adventure-agent/client.tsx +38 -98
  355. package/dist/templates/text-adventure-agent/shared.ts +31 -143
  356. package/dist/templates/text-adventure-agent/tools/game_state_drop.ts +6 -12
  357. package/dist/templates/text-adventure-agent/tools/game_state_get.ts +4 -11
  358. package/dist/templates/text-adventure-agent/tools/game_state_move.ts +0 -2
  359. package/dist/templates/text-adventure-agent/tools/game_state_restart.ts +1 -3
  360. package/dist/templates/text-adventure-agent/tools/game_state_score.ts +5 -7
  361. package/dist/templates/topic-briefing-agent/agent.eval.test.ts +12 -50
  362. package/dist/templates/topic-briefing-agent/agent.test.ts +478 -476
  363. package/dist/templates/topic-briefing-agent/agent.ts +3 -3
  364. package/dist/templates/topic-briefing-agent/shared.ts +11 -16
  365. package/dist/templates/topic-briefing-agent/slack.ts +12 -4
  366. package/dist/templates/topic-briefing-agent/tools/briefing_so_far.ts +10 -17
  367. package/dist/templates/topic-briefing-agent/tools/research_topic.ts +21 -24
  368. package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +13 -14
  369. package/dist/templates/topic-briefing-agent/tools/verify_claim.ts +16 -13
  370. package/dist/templates/transcription-workflow/agent.test.ts +114 -259
  371. package/dist/templates/transcription-workflow/agent.ts +6 -9
  372. package/dist/templates/transcription-workflow/client.tsx +100 -258
  373. package/dist/templates/transcription-workflow/recover.test.ts +6 -136
  374. package/dist/templates/transcription-workflow/recover.ts +14 -97
  375. package/dist/templates/transcription-workflow/run-panel.tsx +71 -8
  376. package/dist/templates/transcription-workflow/workflows/batch.ts +28 -159
  377. package/dist/templates/transcription-workflow/workflows/normalize.ts +50 -86
  378. package/dist/templates/transcription-workflow/workflows/stream.ts +2 -2
  379. package/dist/templates/transcription-workflow/workflows/transcribe.ts +16 -23
  380. package/dist/templates/travel-concierge-agent/agent.eval.test.ts +7 -25
  381. package/dist/templates/travel-concierge-agent/agent.test.ts +505 -517
  382. package/dist/templates/travel-concierge-agent/agent.ts +22 -46
  383. package/dist/templates/travel-concierge-agent/client.tsx +1 -22
  384. package/dist/templates/travel-concierge-agent/routing.ts +29 -31
  385. package/dist/templates/travel-concierge-agent/shared.ts +63 -152
  386. package/dist/templates/travel-concierge-agent/tools/book_car_rental.ts +8 -9
  387. package/dist/templates/travel-concierge-agent/tools/book_excursion.ts +8 -8
  388. package/dist/templates/travel-concierge-agent/tools/book_hotel.ts +9 -6
  389. package/dist/templates/travel-concierge-agent/tools/cancel_ticket.ts +10 -10
  390. package/dist/templates/travel-concierge-agent/tools/search_car_rentals.ts +3 -2
  391. package/dist/templates/travel-concierge-agent/tools/search_excursions.ts +3 -2
  392. package/dist/templates/travel-concierge-agent/tools/search_flights.ts +4 -3
  393. package/dist/templates/travel-concierge-agent/tools/search_hotels.ts +3 -2
  394. package/dist/templates/travel-concierge-agent/tools/update_ticket.ts +13 -8
  395. package/dist/templates/web-research-agent/agent.test.ts +19 -30
  396. package/dist/templates/web-research-agent/agent.ts +3 -4
  397. package/dist/templates/word-game-agent/agent.eval.test.ts +47 -67
  398. package/dist/templates/word-game-agent/agent.test.ts +369 -382
  399. package/dist/templates/word-game-agent/agent.ts +2 -5
  400. package/dist/templates/word-game-agent/client.tsx +1 -8
  401. package/dist/templates/word-game-agent/game.ts +15 -27
  402. package/dist/templates/word-game-agent/shared.ts +36 -20
  403. package/dist/templates/word-game-agent/tools/final_score.ts +14 -13
  404. package/dist/templates/word-game-agent/tools/relay_description.ts +90 -66
  405. package/dist/templates/word-game-agent/tools/repeat_word.ts +11 -10
  406. package/dist/templates/word-game-agent/tools/skip_word.ts +17 -21
  407. package/dist/templates/word-game-agent/tools/start_game.ts +26 -30
  408. package/dist/{test-XufelYGW.mjs → test-CW5cw5fy.mjs} +3 -4
  409. package/dist/typecheck.mjs +1 -1
  410. package/dist/worker-bundler-D8uCzpYP.mjs +335 -0
  411. package/dist/worker-bundler.d.ts +39 -0
  412. package/dist/worker-bundler.mjs +2 -155
  413. package/dist/{workflow-CDUlTD5B.mjs → workflow-5gOZMB2M.mjs} +66 -19
  414. package/package.json +4 -4
  415. package/dist/_output-DBP9Op_d.mjs +0 -120
  416. package/dist/_studio-B5m4jBTD.mjs +0 -256
  417. package/dist/_ui-Coe0zwmm.mjs +0 -102
  418. package/dist/_utils-BVLdBvdT.mjs +0 -186
  419. package/dist/delete-DwXCHzTl.mjs +0 -55
  420. package/dist/templates/document-redline-workflow/form.ts +0 -73
  421. package/dist/templates/emergency-dispatch-agent/events.ts +0 -48
  422. package/dist/templates/hotel-reception-agent/events.ts +0 -80
  423. package/dist/templates/meeting-recap-agent/shared.ts +0 -44
  424. package/dist/templates/meeting-recap-agent/tools/cancel_recap.ts +0 -25
  425. package/dist/templates/meeting-recap-agent/tools/recap_progress.ts +0 -24
  426. package/dist/templates/meeting-recap-agent/tools/recap_status.ts +0 -45
  427. package/dist/templates/meeting-recap-agent/workflows/tokens.ts +0 -47
  428. package/dist/templates/outbound-call-agent/call-params.ts +0 -109
  429. package/dist/templates/outbound-call-agent/live-calls.ts +0 -80
  430. package/dist/templates/outbound-call-agent/workflows/tokens.ts +0 -16
  431. package/dist/templates/research-handoff-agent/shared.ts +0 -41
  432. package/dist/templates/research-handoff-agent/tools/research_progress.ts +0 -23
  433. package/dist/templates/research-handoff-agent/tools/research_status.ts +0 -73
  434. package/dist/templates/research-handoff-agent/workflows/review.ts +0 -43
  435. package/dist/templates/roadside-assistance-agent/events.ts +0 -92
  436. package/dist/templates/spoken-summary-workflow/workflows/transcribe.ts +0 -137
  437. package/dist/templates/transcription-workflow/total-latency.tsx +0 -170
  438. package/dist/templates/travel-concierge-agent/call-events.ts +0 -80
package/dist/start.mjs CHANGED
@@ -1,16 +1,764 @@
1
1
  #!/usr/bin/env node
2
- import { t as defaultUi } from "./_ui-Coe0zwmm.mjs";
2
+ import { a as isProtocolMessage, c as nodeCluster, l as superviseWorkers, n as SLOTS_ENV, o as isStartWorker, r as SLOT_ENV, s as loadCluster } from "./_start-workers-BNdOnTal.mjs";
3
+ import { t as defaultUi } from "./_ui-C0RufoYZ.mjs";
3
4
  import { n as WORKER_ARTIFACT_REL, t as CLIENT_ARTIFACT_REL } from "./_artifacts-BJOYGQPp.mjs";
4
5
  import { t as resolveDenoRunCode } from "./_run-code-deno-C0AtfHeH.mjs";
5
- import { i as resolveServerEnv, n as DEPLOY_ENV_FILES } from "./_server-common-CVXIeWrY.mjs";
6
+ import { a as resolveServerEnv, n as DEPLOY_ENV_FILES } from "./_server-common-C6j67AcZ.mjs";
6
7
  import { existsSync } from "node:fs";
7
8
  import path from "node:path";
8
9
  import { pathToFileURL } from "node:url";
9
- import { omitUndefined } from "@alexkroman1/aai/utils";
10
+ import { isRecord, omitUndefined } from "@alexkroman1/aai/utils";
11
+ import { parseWsUpgradeParams, requestPath, sleep } from "@alexkroman1/aai/internal";
10
12
  import { createAgentServer, ensureSessionStateSchema, ensureWorkflowJournalSchema } from "@alexkroman1/aai-runtime";
11
- import { consoleLogger, withHostCredentialFallback } from "@alexkroman1/aai-runtime/internal";
13
+ import { SERVER_ROUTES, consoleLogger, notifyClientHere, routeMatches, setClientNotifyRelay, setSessionIdMinter, withHostCredentialFallback } from "@alexkroman1/aai-runtime/internal";
12
14
  import { startTracing } from "@alexkroman1/aai-runtime/tracing";
13
15
  import { defaultClientDir } from "@alexkroman1/aai-ui/client-dir";
16
+ import http from "node:http";
17
+ import { randomUUID } from "node:crypto";
18
+ import { Socket } from "node:net";
19
+ import { performance } from "node:perf_hooks";
20
+ //#region src/_start-log.ts
21
+ /**
22
+ * The runtime's logger for `aai start`: the console logger in human mode, and
23
+ * in JSON mode the same lines on STDERR.
24
+ *
25
+ * `console.log` is stdout, so in JSON mode the runtime's boot dump landed ahead
26
+ * of the one result line the command owes there — the hazard
27
+ * `createDevLogger` (`_dev-env.ts`) fixed for `aai dev`. It matters more here:
28
+ * JSON mode is auto-selected without a TTY, which is every container `aai
29
+ * start` runs in. Unlike the dev logger this keeps the console formatting and
30
+ * its ISO timestamps (a server's log is read by time) by sending info through
31
+ * `console.warn`, the console logger's stderr writer. `debug` stays as it is:
32
+ * it is silent unless `AAI_DEBUG` asks for it.
33
+ */
34
+ function startLogger(silenced, base = consoleLogger) {
35
+ if (!silenced) return base;
36
+ return {
37
+ info: base.warn,
38
+ warn: base.warn,
39
+ error: base.error,
40
+ debug: base.debug
41
+ };
42
+ }
43
+ /**
44
+ * A `--workers` worker's logger: every line tagged `[worker N]` with its slot,
45
+ * and slot 0 alone saying what happens while it boots.
46
+ *
47
+ * Without the tag, a session's lines from four workers interleave with nothing
48
+ * to say which process — or which `/workers` row — wrote them. Without the
49
+ * quieting, `--workers auto` on a 32-core box printed the multi-line
50
+ * "Session mode resolved" dump, "Serving" and the uploads notice 32 times: they
51
+ * are a function of the build and its env, identical in every slot, so one
52
+ * copy says everything. Only INFO is quieted, and only until {@link booted};
53
+ * a warning or error at boot can be one slot's own, and after boot info is the
54
+ * session log, which is every slot's own.
55
+ */
56
+ function workerLogger(base, slot) {
57
+ let quiet = slot !== 0;
58
+ const tag = (fn) => (message, ctx) => fn(`[worker ${slot}] ${message}`, ctx);
59
+ const info = tag(base.info);
60
+ return {
61
+ logger: {
62
+ info: (message, ctx) => {
63
+ if (!quiet) info(message, ctx);
64
+ },
65
+ warn: tag(base.warn),
66
+ error: tag(base.error),
67
+ debug: tag(base.debug)
68
+ },
69
+ booted: () => {
70
+ quiet = false;
71
+ }
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region src/_start-affinity.ts
76
+ /**
77
+ * Which `aai start --workers` worker a request belongs to.
78
+ *
79
+ * A browser's session, its `/inbox` socket and its `/api` calls must all reach
80
+ * ONE worker: the session lives in that worker's memory, the inbox's event feed
81
+ * is fed from the session's process, and an `/api` route's `ctx.speech` speaks
82
+ * into a session it can only see locally. So requests are routed by the thing
83
+ * they share, the way LiveKit routes by room:
84
+ *
85
+ * 1. the CLIENT (`?client=`), which `aai-ui` sends on `/websocket`, `/inbox`
86
+ * and every route call, and which outlives any one session;
87
+ * 2. else the SESSION — `?sessionId=` on a resume, or the `sid` a session
88
+ * ticket carries (readable without the secret: the payload is base64url
89
+ * JSON, the HMAC only authenticates it — `session-ticket.ts` in the runtime);
90
+ * 3. else nothing, and the router deals the request round-robin.
91
+ *
92
+ * A key maps to a slot by hash, so routing needs no table. A worker mints fresh
93
+ * session ids that hash to ITS OWN slot ({@link mintIdForSlot}), which is what
94
+ * makes rule 2 land a resume where the session is.
95
+ *
96
+ * @module
97
+ */
98
+ /** The `Sec-WebSocket-Protocol` entry a session ticket rides in (`session-protocol.ts` in the SDK). */
99
+ const TICKET_PROTOCOL_PREFIX = "aai.auth.";
100
+ /** The routing key for a client id — namespaced, so a client and a session never collide. */
101
+ function clientKey(clientId) {
102
+ return `client:${clientId}`;
103
+ }
104
+ /** The routing key for a session id. */
105
+ function sessionKey(sessionId) {
106
+ return `session:${sessionId}`;
107
+ }
108
+ /**
109
+ * FNV-1a (32-bit) of `key`, avalanched with MurmurHash3's finalizer, reduced to
110
+ * `slots`. Stable across processes and restarts. The finalizer matters: FNV's
111
+ * low bits mix poorly, so ids that differ only at the end (`phone-1`,
112
+ * `phone-2`, …) would fall into a regular pattern modulo a small worker count.
113
+ */
114
+ function slotOf(key, slots) {
115
+ let hash = 2166136261;
116
+ for (let i = 0; i < key.length; i++) {
117
+ hash ^= key.charCodeAt(i);
118
+ hash = Math.imul(hash, 16777619);
119
+ }
120
+ hash ^= hash >>> 16;
121
+ hash = Math.imul(hash, 2246822507);
122
+ hash ^= hash >>> 13;
123
+ hash = Math.imul(hash, 3266489909);
124
+ hash ^= hash >>> 16;
125
+ return (hash >>> 0) % slots;
126
+ }
127
+ /**
128
+ * A fresh session id that routes to `slot` — rejection sampling over random
129
+ * UUIDs, ~`slots` tries on average. Still a full random UUID, so it is exactly
130
+ * as unguessable as the default.
131
+ */
132
+ function mintIdForSlot(slot, slots, uuid = randomUUID) {
133
+ for (;;) {
134
+ const id = uuid();
135
+ if (slotOf(sessionKey(id), slots) === slot) return id;
136
+ }
137
+ }
138
+ /** The `sid` a session ticket carries, or `undefined` for anything that is not one. */
139
+ function ticketSessionId(ticket) {
140
+ const body = ticket.split(".")[0];
141
+ if (!body) return void 0;
142
+ try {
143
+ const sid = JSON.parse(Buffer.from(body, "base64url").toString("utf8"))?.sid;
144
+ return typeof sid === "string" && sid.length > 0 ? sid : void 0;
145
+ } catch {
146
+ return;
147
+ }
148
+ }
149
+ /**
150
+ * The `sid` of the ticket a request presents — the auth subprotocol first,
151
+ * then `?token=` (the runtime's order) — or `undefined`.
152
+ */
153
+ function presentedTicketSid(url, headers) {
154
+ const raw = headers["sec-websocket-protocol"];
155
+ const header = Array.isArray(raw) ? raw.join(",") : raw;
156
+ for (const entry of header?.split(",") ?? []) {
157
+ const protocol = entry.trim();
158
+ if (protocol.startsWith(TICKET_PROTOCOL_PREFIX)) return ticketSessionId(protocol.slice(9));
159
+ }
160
+ const token = url.searchParams.get("token");
161
+ return token ? ticketSessionId(token) : void 0;
162
+ }
163
+ /**
164
+ * The routing key of one request, or `undefined` when nothing ties it to a
165
+ * worker. See the module doc for the order.
166
+ */
167
+ function affinityKey(rawUrl, headers) {
168
+ const url = new URL(rawUrl ?? "/", "http://route.invalid");
169
+ const client = url.searchParams.get("client")?.trim();
170
+ if (client) return clientKey(client);
171
+ const ticketSid = presentedTicketSid(url, headers);
172
+ if (ticketSid) return sessionKey(ticketSid);
173
+ const sessionId = url.searchParams.get("sessionId")?.trim();
174
+ return sessionId ? sessionKey(sessionId) : void 0;
175
+ }
176
+ /**
177
+ * Is this upgrade a CALL — a voice session or a phone call — as opposed to an
178
+ * `/inbox` socket? Decided with the server's own route table and matcher
179
+ * (`routeMatches`, a PREFIX match for both) over the same `requestPath` it
180
+ * routes by. Matching here any other way would be a parser differential: a
181
+ * spelling the server treats as a session (`/websocket/x`) that admission and
182
+ * the drain's call count would not see.
183
+ */
184
+ function isCallPath(rawUrl) {
185
+ const path = requestPath(rawUrl ?? "/");
186
+ return routeMatches(SERVER_ROUTES.session, path) || routeMatches(SERVER_ROUTES.phone, path);
187
+ }
188
+ /**
189
+ * Does this request continue a session that already exists (a reconnect), as
190
+ * opposed to starting one? The runtime's own reading: `parseWsUpgradeParams`'s
191
+ * `resumeFrom` (a malformed id is no resume), or a ticket that names a session.
192
+ *
193
+ * This is a CLAIM the client makes, not a fact — the runtime starts a fresh
194
+ * session under an id it has never seen. So it only ever exempts a request from
195
+ * the DRAIN (whose worst case is a call that ends at the drain timeout, like
196
+ * every other), never from the per-worker cap.
197
+ */
198
+ function isResume(rawUrl, headers) {
199
+ if (parseWsUpgradeParams(rawUrl ?? "/").resumeFrom !== void 0) return true;
200
+ return presentedTicketSid(new URL(rawUrl ?? "/", "http://route.invalid"), headers) !== void 0;
201
+ }
202
+ //#endregion
203
+ //#region src/_start-router.ts
204
+ /**
205
+ * The `aai start --workers` primary's public listener: route each request to
206
+ * the worker its affinity key names (`_start-affinity.ts`).
207
+ *
208
+ * Two kinds of traffic, routed at two layers on purpose:
209
+ *
210
+ * - **A WebSocket upgrade** (`/websocket`, `/inbox`, `/phone`) is handed to the
211
+ * worker as the raw socket, with the request bytes replayed. After the
212
+ * handoff the primary never touches the connection again — every audio frame
213
+ * goes straight to the worker, so the primary cannot become the bottleneck
214
+ * the workers exist to remove.
215
+ * - **Plain HTTP** (`/api/*`, `/workflows/*`, `/client-config`, …) is proxied
216
+ * PER REQUEST to the worker's private loopback port. Routing per connection
217
+ * would be wrong behind any reverse proxy that pools upstream connections:
218
+ * many clients share one keep-alive connection, and every request on it would
219
+ * follow the first. This traffic is light, so the proxy hop is cheap.
220
+ *
221
+ * A keyed request whose worker is restarting gets `503` with `Retry-After`
222
+ * rather than another worker: the session it names lives only in its own
223
+ * worker, and a client retrying in a second beats one silently forked.
224
+ *
225
+ * @module
226
+ */
227
+ /** How long a client may take to send its request head before it is dropped. */
228
+ const HEADERS_TIMEOUT_MS = 15e3;
229
+ /**
230
+ * How often the server sweeps for connections past {@link HEADERS_TIMEOUT_MS}.
231
+ * Node's default is 30 s, so a slow-headers client actually held its socket
232
+ * for 15–45 s (measured: 2000 idle half-sent heads all still open at 18 s).
233
+ */
234
+ const CONNECTIONS_CHECK_MS = 2e3;
235
+ /** Headers that describe ONE hop and must not be forwarded (RFC 9110 §7.6.1). */
236
+ const HOP_BY_HOP = /* @__PURE__ */ new Set([
237
+ "connection",
238
+ "keep-alive",
239
+ "proxy-authenticate",
240
+ "proxy-authorization",
241
+ "proxy-connection",
242
+ "te",
243
+ "trailer",
244
+ "transfer-encoding",
245
+ "upgrade"
246
+ ]);
247
+ function endToEnd(headers) {
248
+ const out = {};
249
+ for (const [name, value] of Object.entries(headers)) if (!HOP_BY_HOP.has(name)) out[name] = value;
250
+ return out;
251
+ }
252
+ /** The request head, re-serialized byte-for-byte from what the parser saw, for a handoff. */
253
+ function serializeRequestHead(req) {
254
+ let head = `${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`;
255
+ const raw = req.rawHeaders;
256
+ for (let i = 0; i < raw.length; i += 2) head += `${raw[i]}: ${raw[i + 1]}\r\n`;
257
+ return Buffer.from(`${head}\r\n`, "latin1");
258
+ }
259
+ /** Why a new call is refused, as the 503 body says it. */
260
+ const REFUSAL = {
261
+ draining: "server is draining for a restart; retry against another instance",
262
+ full: "this worker is at its call limit; retry shortly"
263
+ };
264
+ /** Loopback peers — the only ones `GET /workers` answers. */
265
+ const LOOPBACK = /* @__PURE__ */ new Set([
266
+ "127.0.0.1",
267
+ "::1",
268
+ "::ffff:127.0.0.1"
269
+ ]);
270
+ /**
271
+ * Pick the worker for a request: its key's slot when it has a key (and only
272
+ * that slot — `undefined` while it restarts), else the next listening slot in turn.
273
+ */
274
+ function createSlotPicker(opts) {
275
+ let next = 0;
276
+ const at = (slot) => {
277
+ const worker = opts.target(slot);
278
+ return worker && {
279
+ slot,
280
+ worker
281
+ };
282
+ };
283
+ return (key) => {
284
+ if (key !== void 0) return at(slotOf(key, opts.slots));
285
+ for (let i = 0; i < opts.slots; i++) {
286
+ const picked = at((next + i) % opts.slots);
287
+ if (picked) {
288
+ next = picked.slot + 1;
289
+ return picked;
290
+ }
291
+ }
292
+ };
293
+ }
294
+ function unavailable(res, reason = "worker restarting, retry shortly") {
295
+ res.writeHead(503, {
296
+ "retry-after": "1",
297
+ "content-type": "text/plain"
298
+ });
299
+ res.end(`${reason}\n`);
300
+ }
301
+ function proxy(req, res, worker, request) {
302
+ const upstream = request({
303
+ host: "127.0.0.1",
304
+ port: worker.port,
305
+ method: req.method,
306
+ path: req.url,
307
+ headers: endToEnd(req.headers)
308
+ }, (reply) => {
309
+ res.writeHead(reply.statusCode ?? 502, reply.statusMessage, endToEnd(reply.headers));
310
+ reply.pipe(res);
311
+ });
312
+ upstream.on("error", () => {
313
+ if (!res.headersSent) {
314
+ res.writeHead(502, { "content-type": "text/plain" }).end();
315
+ return;
316
+ }
317
+ res.destroy();
318
+ });
319
+ res.on("close", () => {
320
+ if (!res.writableFinished) upstream.destroy();
321
+ });
322
+ req.pipe(upstream);
323
+ }
324
+ function refuseUpgrade(socket, reason = "worker restarting, retry shortly") {
325
+ const body = `${reason}\n`;
326
+ socket.end(`HTTP/1.1 503 Service Unavailable\r
327
+ Retry-After: 1\r
328
+ Connection: close\r
329
+ Content-Type: text/plain\r\nContent-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);
330
+ }
331
+ /**
332
+ * Stop THIS process reading `socket` before its handle goes to a worker.
333
+ *
334
+ * Node leaves the handle reading after an upgrade, and the IPC send detaches
335
+ * it only when the send actually happens — after the ack of every handle
336
+ * queued ahead of it — then closes it only on this one's ack. Bytes the client
337
+ * sends meanwhile (a client that writes before the 101, or simply racing the
338
+ * ack) are read HERE and dropped, and the worker sees a stream with a hole in
339
+ * it: a corrupt WebSocket frame. Measured with real IPC and pipelining
340
+ * clients: 12–23 of 300 concurrent handoffs lost bytes; with this, none of
341
+ * 3000. `pause()` is no
342
+ * substitute — it stops the stream, not the handle. Stopped, the bytes wait in
343
+ * the kernel for the worker's own read.
344
+ */
345
+ function stopReading(socket) {
346
+ const handle = Reflect.get(socket, "_handle");
347
+ if (isRecord(handle) && typeof handle.readStop === "function") handle.readStop();
348
+ }
349
+ /** A load balancer's probe: `GET`/`HEAD` on the server's own health route. */
350
+ function isHealthProbe(req) {
351
+ const { health } = SERVER_ROUTES;
352
+ return (req.method === "GET" || req.method === "HEAD") && routeMatches(health, requestPath(req.url ?? "/"));
353
+ }
354
+ /** The primary's public server. The caller binds it. */
355
+ function createRouter(opts) {
356
+ const pick = createSlotPicker(opts);
357
+ const server = http.createServer({ connectionsCheckingInterval: CONNECTIONS_CHECK_MS }, (req, res) => {
358
+ if (opts.status && req.method === "GET" && req.url === "/workers") {
359
+ if (!LOOPBACK.has(req.socket.remoteAddress ?? "")) {
360
+ res.writeHead(404).end();
361
+ return;
362
+ }
363
+ res.writeHead(200, { "content-type": "application/json" });
364
+ res.end(JSON.stringify({ workers: opts.status() }));
365
+ return;
366
+ }
367
+ const notReady = opts.notReady?.();
368
+ if (notReady && isHealthProbe(req)) return unavailable(res, notReady);
369
+ const picked = pick(affinityKey(req.url, req.headers));
370
+ if (!picked) return unavailable(res);
371
+ proxy(req, res, picked.worker, opts.request ?? http.request);
372
+ });
373
+ server.headersTimeout = HEADERS_TIMEOUT_MS;
374
+ server.on("upgrade", (req, socket, head) => {
375
+ const picked = pick(affinityKey(req.url, req.headers));
376
+ if (!picked) return refuseUpgrade(socket);
377
+ const call = isCallPath(req.url);
378
+ if (call) {
379
+ const verdict = opts.admitCall?.(picked.slot, isResume(req.url, req.headers)) ?? "ok";
380
+ if (verdict !== "ok") return refuseUpgrade(socket, REFUSAL[verdict]);
381
+ }
382
+ const bytes = Buffer.concat([serializeRequestHead(req), head]);
383
+ stopReading(socket);
384
+ if (!picked.worker.worker.send({
385
+ type: "aai-start:upgrade",
386
+ bytes,
387
+ call
388
+ }, socket)) refuseUpgrade(socket);
389
+ });
390
+ return server;
391
+ }
392
+ //#endregion
393
+ //#region src/_start-worker.ts
394
+ /**
395
+ * One `aai start --workers` worker joining its primary.
396
+ *
397
+ * The worker serves the ordinary `AgentServer`, reached two ways and never on
398
+ * the public port (the primary owns that — `_start-router.ts`):
399
+ *
400
+ * - a WebSocket upgrade arrives over IPC as the raw socket plus the request
401
+ * bytes the primary already read; they go back into the socket's buffer and
402
+ * the socket is handed to this server's HTTP listener as a new connection;
403
+ * - plain HTTP arrives proxied on a private loopback port.
404
+ *
405
+ * It also installs this process's two runtime seams: session ids are minted to
406
+ * hash to this worker's slot (so a resume naming only the id routes here), and
407
+ * an `/inbox` notice for a client another worker owns is relayed through the
408
+ * primary to that worker, which delivers it locally.
409
+ *
410
+ * @module
411
+ */
412
+ /** The real link: this process's IPC channel. */
413
+ function processLink(proc = process) {
414
+ return {
415
+ send: (message) => {
416
+ proc.send?.(message);
417
+ },
418
+ onMessage: (listener) => {
419
+ proc.on("message", (message, handle) => {
420
+ if (!isProtocolMessage(message)) return;
421
+ listener(message, handle instanceof Socket ? handle : void 0);
422
+ });
423
+ }
424
+ };
425
+ }
426
+ /** The refusal a worker reports when the agent needs state it cannot share. */
427
+ function workflowsNeedDatabase(workers) {
428
+ return `This agent declares workflows, and running it on ${workers} workers needs DATABASE_URL: a run started on one worker must be readable and resumable from every other. Set DATABASE_URL (any Postgres), or run with \`--workers 1\`.`;
429
+ }
430
+ const realRuntime = {
431
+ setSessionIdMinter,
432
+ setClientNotifyRelay,
433
+ notifyClientHere
434
+ };
435
+ /** Install the relay client: a notice for a client another slot owns goes through the primary. */
436
+ function installRelayClient(slot, slots, link, runtime) {
437
+ let nextId = 0;
438
+ const pending = /* @__PURE__ */ new Map();
439
+ runtime.setClientNotifyRelay({ forward(clientId) {
440
+ const target = slotOf(clientKey(clientId), slots);
441
+ if (target === slot) return;
442
+ const viaPrimary = (id, notice, { ackTimeoutMs, signal }) => new Promise((resolve, reject) => {
443
+ if (signal?.aborted) return reject(signal.reason);
444
+ const relayId = ++nextId;
445
+ const onAbort = () => {
446
+ if (!pending.delete(relayId)) return;
447
+ link.send({
448
+ type: "aai-start:relay-cancel",
449
+ id: relayId,
450
+ target
451
+ });
452
+ reject(signal?.reason);
453
+ };
454
+ pending.set(relayId, (outcome) => {
455
+ signal?.removeEventListener("abort", onAbort);
456
+ resolve(outcome);
457
+ });
458
+ signal?.addEventListener("abort", onAbort, { once: true });
459
+ link.send({
460
+ type: "aai-start:relay",
461
+ id: relayId,
462
+ target,
463
+ payload: {
464
+ op: "notify",
465
+ clientId: id,
466
+ notice,
467
+ ackTimeoutMs
468
+ }
469
+ });
470
+ });
471
+ return viaPrimary;
472
+ } });
473
+ return (id, outcome) => {
474
+ const settle = pending.get(id);
475
+ pending.delete(id);
476
+ settle?.(outcome);
477
+ };
478
+ }
479
+ /**
480
+ * Serve `server` as worker `slot` of `slots`: install the seams, bind the
481
+ * private port, and report listening. Resolves once reported.
482
+ */
483
+ async function joinCluster(opts) {
484
+ const { slot, slots, server, link, runtime = realRuntime } = opts;
485
+ /** Live call sockets: incremented at handoff, decremented when the socket closes. */
486
+ let calls = 0;
487
+ /** Call sockets ever handed over — lets the primary count the ones still in transit. */
488
+ let received = 0;
489
+ let eluMark = performance.eventLoopUtilization();
490
+ runtime.setSessionIdMinter(() => mintIdForSlot(slot, slots));
491
+ const settleRelay = installRelayClient(slot, slots, link, runtime);
492
+ /** Relayed notices this worker is delivering, by the primary's id, so a cancel can abort one. */
493
+ const delivering = /* @__PURE__ */ new Map();
494
+ link.onMessage((message, socket) => {
495
+ switch (message.type) {
496
+ case "aai-start:upgrade":
497
+ if (!socket) return;
498
+ if (message.call) {
499
+ calls += 1;
500
+ received += 1;
501
+ socket.once("close", () => {
502
+ calls -= 1;
503
+ });
504
+ }
505
+ socket.unshift(Buffer.from(message.bytes));
506
+ server.node.emit("connection", socket);
507
+ socket.resume();
508
+ return;
509
+ case "aai-start:relay": {
510
+ const control = new AbortController();
511
+ delivering.set(message.id, control);
512
+ const { clientId, notice, ackTimeoutMs } = message.payload;
513
+ runtime.notifyClientHere(clientId, notice, {
514
+ ackTimeoutMs,
515
+ signal: control.signal
516
+ }).catch(() => "disconnected").then((outcome) => {
517
+ if (!delivering.delete(message.id)) return;
518
+ link.send({
519
+ type: "aai-start:relay-result",
520
+ id: message.id,
521
+ outcome
522
+ });
523
+ });
524
+ return;
525
+ }
526
+ case "aai-start:relay-cancel": {
527
+ const control = delivering.get(message.id);
528
+ delivering.delete(message.id);
529
+ control?.abort(/* @__PURE__ */ new Error("relayed notice cancelled by its sender"));
530
+ return;
531
+ }
532
+ case "aai-start:relay-result":
533
+ settleRelay(message.id, message.outcome);
534
+ return;
535
+ case "aai-start:ping": {
536
+ const elu = performance.eventLoopUtilization(eluMark);
537
+ eluMark = performance.eventLoopUtilization();
538
+ link.send({
539
+ type: "aai-start:pong",
540
+ calls,
541
+ received,
542
+ elu: Math.round(elu.utilization * 1e3) / 1e3
543
+ });
544
+ return;
545
+ }
546
+ case "aai-start:drain":
547
+ opts.close?.(message.timeoutMs);
548
+ return;
549
+ case "aai-start:stop":
550
+ opts.close?.(0);
551
+ return;
552
+ default: return;
553
+ }
554
+ });
555
+ await server.listen(0, "127.0.0.1");
556
+ if (server.port === void 0) throw new Error("worker could not bind its private port");
557
+ link.send({
558
+ type: "aai-start:listening",
559
+ name: opts.name,
560
+ port: server.port
561
+ });
562
+ return { activeCalls: () => calls };
563
+ }
564
+ /** A taken port, said in the operator's terms rather than as a raw `EADDRINUSE`. */
565
+ function bindError(error, port) {
566
+ if (!(error instanceof Error && "code" in error && error.code === "EADDRINUSE")) return error;
567
+ return new Error(`port ${port} is in use; pass --port or set PORT`, { cause: error });
568
+ }
569
+ /** Close the server and flush tracing, then exit: 0, or 1 with the failure reported. */
570
+ function shutdown(server, tracing, deps) {
571
+ return deps.stop(server, tracing).then(() => deps.exit(0), (error) => {
572
+ deps.ui.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
573
+ deps.exit(1);
574
+ });
575
+ }
576
+ /**
577
+ * Shut down on the FIRST signal only.
578
+ *
579
+ * `on` with a latch rather than `once`: a second delivery to a `once` listener
580
+ * would take the default action mid-shutdown. The handler is synchronous: a
581
+ * rejected close becomes a non-zero exit, not an unhandled rejection.
582
+ */
583
+ function stopOnSignal(server, tracing, deps) {
584
+ let stopping = false;
585
+ deps.onSignal(() => {
586
+ if (stopping) return;
587
+ stopping = true;
588
+ shutdown(server, tracing, deps);
589
+ });
590
+ }
591
+ /** Serve the built agent: one process, the `--workers` primary, or a worker. */
592
+ async function runStart(target, deps) {
593
+ if (deps.isWorker) return serveAsWorker(deps);
594
+ if (target.workers > 1) return startPrimary(target, deps);
595
+ const tracing = await deps.startTracing();
596
+ const project = await deps.load();
597
+ const server = await deps.build(project);
598
+ await server.listen(target.port, target.host).catch((error) => {
599
+ throw bindError(error, target.port);
600
+ });
601
+ deps.ui.info(`${project.agent.name} listening on http://${target.host ?? "127.0.0.1"}:${server.port}`);
602
+ stopOnSignal(server, tracing, deps);
603
+ return {
604
+ ok: true,
605
+ data: {
606
+ name: project.agent.name,
607
+ port: server.port,
608
+ workers: 1
609
+ }
610
+ };
611
+ }
612
+ /**
613
+ * A `--workers` worker: refuse an agent with workflows and no database (a run
614
+ * must be readable from every worker), build, and join the primary — which owns
615
+ * the public port, the announcement, the command's result AND this worker's
616
+ * lifecycle. So a worker prints no result (`--json` owes ONE line), never
617
+ * settles, and ignores signals: a terminal's Ctrl-C reaches it too, and acting
618
+ * on that would end its calls in the middle of the primary's drain.
619
+ *
620
+ * A failure is told to the primary (WHY, so its error names the cause rather
621
+ * than "a worker exited") and ends the process; the primary reports it ONCE as
622
+ * the command's error. Not to stderr as well: every worker fails the same way,
623
+ * so N workers printed the same paragraph N times before the command's copy.
624
+ */
625
+ async function serveAsWorker(deps) {
626
+ deps.ignoreSignals();
627
+ const link = deps.link();
628
+ const { slot, slots } = deps.slot();
629
+ try {
630
+ const tracing = await deps.startTracing();
631
+ const { agent, env } = await deps.load();
632
+ if (!env.DATABASE_URL && Object.keys(agent.workflows ?? {}).length > 0) throw new Error(workflowsNeedDatabase(slots));
633
+ const server = await deps.build({
634
+ agent,
635
+ env
636
+ });
637
+ let close = () => void 0;
638
+ const { activeCalls } = await joinCluster({
639
+ slot,
640
+ slots,
641
+ server,
642
+ name: agent.name,
643
+ link,
644
+ runtime: deps.runtime,
645
+ close: (graceMs) => close(graceMs)
646
+ });
647
+ close = workerCloser(server, activeCalls, tracing, deps);
648
+ deps.booted?.();
649
+ } catch (error) {
650
+ link.send({
651
+ type: "aai-start:fatal",
652
+ message: error instanceof Error ? error.message : String(error)
653
+ });
654
+ deps.exit(1);
655
+ }
656
+ return deps.forever();
657
+ }
658
+ /**
659
+ * How a worker ends: wait (up to `graceMs`) for its calls to finish, then close
660
+ * the server and exit. A drain passes its timeout; a stop passes 0 — and a stop
661
+ * arriving mid-drain cuts the wait short. Closing happens once.
662
+ */
663
+ function workerCloser(server, activeCalls, tracing, deps) {
664
+ let deadline;
665
+ let waited = 0;
666
+ return (graceMs) => {
667
+ const first = deadline === void 0;
668
+ deadline = Math.min(deadline ?? Number.POSITIVE_INFINITY, graceMs);
669
+ if (!first) return;
670
+ (async () => {
671
+ while (activeCalls() > 0 && waited < (deadline ?? 0)) {
672
+ await deps.sleep(250);
673
+ waited += 250;
674
+ }
675
+ await shutdown(server, tracing, deps);
676
+ })();
677
+ };
678
+ }
679
+ /**
680
+ * The `--workers` primary: it owns no sessions and never imports the agent (the
681
+ * name comes from the workers). It binds the public port FIRST — so a taken
682
+ * port fails before anything is forked — and routes nothing until every slot
683
+ * listens: until then each request gets 503 and `/health` says it is starting.
684
+ * Workers ignore signals, so this is where they are interpreted:
685
+ *
686
+ * - the first SIGINT/SIGTERM DRAINS: new calls are refused (503), everything
687
+ * else — a reconnect, an `/api` call, a run read — still routes, `/health`
688
+ * answers 503 so a load balancer stops sending calls, and each worker exits
689
+ * once its calls end or `drainTimeoutMs` passes;
690
+ * - a second one STOPS: every worker closes now;
691
+ * - SIGHUP is a ROLLING RESTART: each slot's worker is replaced by a fresh one
692
+ * that takes the slot's new traffic, while the old one drains its calls.
693
+ *
694
+ * Rejects, with every worker stopped, when a worker fails to boot.
695
+ */
696
+ async function startPrimary(target, deps) {
697
+ deps.assertBuilt();
698
+ const env = await deps.readEnv();
699
+ let supervisor;
700
+ let serving = false;
701
+ const router = createRouter({
702
+ slots: target.workers,
703
+ target: (slot) => serving ? supervisor?.target(slot) : void 0,
704
+ admitCall: (slot, resume) => supervisor?.admit(slot, resume) ?? "draining",
705
+ notReady: () => {
706
+ if (!serving) return "server is starting";
707
+ return supervisor?.accepting() ? void 0 : "server is draining";
708
+ },
709
+ status: () => supervisor?.status() ?? []
710
+ });
711
+ const port = await deps.listen(router, target.port, target.host).catch((error) => {
712
+ throw bindError(error, target.port);
713
+ });
714
+ const workers = superviseWorkers({
715
+ slots: target.workers,
716
+ cluster: deps.cluster(),
717
+ log: (message) => deps.ui.notify("warn", message),
718
+ maxCallsPerWorker: target.maxCallsPerWorker
719
+ });
720
+ supervisor = workers;
721
+ let signals = 0;
722
+ deps.onSignal((signal) => {
723
+ if (signal === "SIGHUP") return workers.roll(target.drainTimeoutMs);
724
+ signals += 1;
725
+ if (signals > 1) return workers.stop();
726
+ deps.ui.notify("warn", `draining: new calls are refused; live calls get up to ${target.drainTimeoutMs / 1e3}s (signal again to stop now)`);
727
+ workers.drain(target.drainTimeoutMs);
728
+ });
729
+ const { name } = await workers.ready.catch((error) => {
730
+ router.close();
731
+ throw error;
732
+ });
733
+ serving = true;
734
+ workers.exited.then((code) => {
735
+ deps.ui.notify("warn", code === 0 ? "every worker has exited; stopping" : "stopping (a worker exited with an error)");
736
+ router.close();
737
+ deps.exit(code);
738
+ });
739
+ deps.ui.info(`${name} listening on http://${target.host ?? "127.0.0.1"}:${port} with ${target.workers} workers`);
740
+ if (!env.DATABASE_URL) deps.ui.notify("warn", `No DATABASE_URL: each of the ${target.workers} workers keeps its own calls in memory. Every client is routed to the same worker each time, so reconnects resume — but a call does not survive its worker crashing. Set DATABASE_URL for that.`);
741
+ return {
742
+ ok: true,
743
+ data: {
744
+ name,
745
+ port,
746
+ workers: target.workers
747
+ }
748
+ };
749
+ }
750
+ /** Bind `server` the way the primary does; the real {@link StartRunDeps.listen}. */
751
+ function listenServer(server, port, host) {
752
+ return new Promise((resolve, reject) => {
753
+ server.once("error", reject);
754
+ server.listen(port, host ?? "127.0.0.1", () => {
755
+ server.off("error", reject);
756
+ const address = server.address();
757
+ resolve(typeof address === "object" && address ? address.port : port);
758
+ });
759
+ });
760
+ }
761
+ //#endregion
14
762
  //#region src/_stop-server.ts
15
763
  /**
16
764
  * Stop what `aai start` started: close the server — which shuts the runtime
@@ -77,6 +825,19 @@ async function stopProjectServer(server, tracing) {
77
825
  */
78
826
  /** The port `aai start` binds when neither an argument nor `PORT` says otherwise. */
79
827
  const DEFAULT_START_PORT = 3e3;
828
+ /** The built worker's path, or a throw saying what to run. */
829
+ function builtAgentPath(cwd) {
830
+ const workerPath = path.join(cwd, WORKER_ARTIFACT_REL);
831
+ if (!existsSync(workerPath)) throw new Error(`No built agent at ${WORKER_ARTIFACT_REL}. Run \`aai build\` first — the scaffold's \`prestart\` script normally does it for you.`);
832
+ return workerPath;
833
+ }
834
+ /** The address `aai start` binds: the option, then `PORT`/`HOST`, then the defaults. */
835
+ function listenAddress(options) {
836
+ return {
837
+ port: options.port ?? Number(process.env.PORT ?? 3e3),
838
+ host: options.host ?? (process.env.HOST?.trim() || void 0)
839
+ };
840
+ }
80
841
  /**
81
842
  * Load the built agent, or fail saying what to run.
82
843
  *
@@ -84,9 +845,7 @@ const DEFAULT_START_PORT = 3e3;
84
845
  * POSIX-looking path is not a valid module specifier.
85
846
  */
86
847
  async function loadBuiltAgent(cwd) {
87
- const workerPath = path.join(cwd, WORKER_ARTIFACT_REL);
88
- if (!existsSync(workerPath)) throw new Error(`No built agent at ${WORKER_ARTIFACT_REL}. Run \`aai build\` first — the scaffold's \`prestart\` script normally does it for you.`);
89
- return (await import(pathToFileURL(workerPath).href)).default;
848
+ return (await import(pathToFileURL(builtAgentPath(cwd)).href)).default;
90
849
  }
91
850
  /**
92
851
  * Static assets to serve at `/`: this project's own built UI when it has one,
@@ -98,7 +857,7 @@ async function loadBuiltAgent(cwd) {
98
857
  function resolveClientDir(cwd) {
99
858
  const built = path.join(cwd, CLIENT_ARTIFACT_REL);
100
859
  if (existsSync(path.join(built, "index.html"))) return built;
101
- if (existsSync(path.join(cwd, "client.tsx"))) defaultUi.log.warn("client.tsx is not built — serving the default UI. Run `aai build` first.");
860
+ if (existsSync(path.join(cwd, "client.tsx"))) defaultUi.notify("warn", "client.tsx is not built — serving the default UI. Run `aai build` first.");
102
861
  return defaultClientDir();
103
862
  }
104
863
  /**
@@ -126,58 +885,99 @@ function resolveClientDir(cwd) {
126
885
  * ```
127
886
  */
128
887
  async function createProjectServer(options) {
129
- const { cwd } = options;
130
- const agent = await loadBuiltAgent(cwd);
131
- const env = await resolveServerEnv(cwd, void 0, DEPLOY_ENV_FILES);
888
+ const { agent, env } = await loadProject(options.cwd);
889
+ return buildProjectServer(options.cwd, agent, env, consoleLogger);
890
+ }
891
+ /** The built agent and its env — what every way of serving a project starts from. */
892
+ async function loadProject(cwd) {
893
+ return {
894
+ agent: await loadBuiltAgent(cwd),
895
+ env: await resolveServerEnv(cwd, void 0, DEPLOY_ENV_FILES)
896
+ };
897
+ }
898
+ async function buildProjectServer(cwd, agent, env, logger) {
132
899
  if (env.DATABASE_URL) {
133
900
  await ensureSessionStateSchema({
134
901
  url: env.DATABASE_URL,
135
- logger: console
902
+ logger
136
903
  });
137
904
  await ensureWorkflowJournalSchema({
138
905
  url: env.DATABASE_URL,
139
- logger: console
906
+ logger
140
907
  });
141
- } else defaultUi.log.warn("No DATABASE_URL: session state and durable runs live in THIS process's memory.\nOne replica is fine. Behind a load balancer, enable sticky sessions so a reconnect (the client re-dials with ?sessionId=) reaches the same process — or set DATABASE_URL and let every replica share the state.");
908
+ } else if (!isStartWorker()) defaultUi.notify("warn", "No DATABASE_URL: session state and durable runs live in THIS process's memory.\nOne replica is fine. Behind a load balancer, enable sticky sessions so a reconnect (the client re-dials with ?sessionId=) reaches the same process — or set DATABASE_URL and let every replica share the state.");
142
909
  return createAgentServer({
143
910
  agent,
144
911
  env,
912
+ logger,
145
913
  providerEnv: withHostCredentialFallback(env),
146
914
  clientDir: resolveClientDir(cwd),
147
915
  ...process.env.PUBLIC_URL?.trim() ? { publicUrl: process.env.PUBLIC_URL.trim() } : {},
148
- ...omitUndefined({ runCode: resolveDenoRunCode(consoleLogger) })
916
+ ...omitUndefined({ runCode: resolveDenoRunCode(logger) })
149
917
  });
150
918
  }
151
919
  /**
152
920
  * Serve the built agent and keep serving it: bind, announce, and shut down
153
- * cleanly on a signal.
154
- *
155
- * The signal listeners are SYNCHRONOUS. An `async` one hands its promise to
156
- * `process`, which discards what a listener returns — so a `close()` that
157
- * rejected would surface as an unhandled rejection, i.e. a crash with a stack
158
- * trace on Ctrl-C, instead of the non-zero exit a failed shutdown should be.
921
+ * cleanly on a signal — from one process, or with `workers > 1` from a primary
922
+ * routing to that many (`_start-workers.ts`). The logic is `runStart`
923
+ * (`_start-run.ts`); this hands it the real process.
159
924
  */
160
925
  async function executeStart(options) {
161
- const tracing = await startTracing();
162
- const agent = await loadBuiltAgent(options.cwd);
163
- const server = await createProjectServer(options);
164
- const port = options.port ?? Number(process.env.PORT ?? 3e3);
165
- const host = options.host ?? (process.env.HOST?.trim() || void 0);
166
- await server.listen(port, host);
167
- defaultUi.log.info(`${agent.name} listening on http://${host ?? "127.0.0.1"}:${server.port}`);
168
- for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => {
169
- stopProjectServer(server, tracing).then(() => process.exit(0), (error) => {
170
- defaultUi.log.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
171
- process.exit(1);
172
- });
173
- });
174
- return {
175
- ok: true,
176
- data: {
177
- name: agent.name,
178
- port: server.port
926
+ const { cwd } = options;
927
+ const { port, host } = listenAddress(options);
928
+ const signals = [
929
+ "SIGINT",
930
+ "SIGTERM",
931
+ "SIGHUP"
932
+ ];
933
+ const base = startLogger(defaultUi.silenced);
934
+ const isWorker = isStartWorker();
935
+ const tagged = isWorker ? workerLogger(base, Number(process.env[SLOT_ENV])) : void 0;
936
+ const logger = tagged?.logger ?? base;
937
+ const workers = options.workers ?? 1;
938
+ const forking = !isWorker && workers > 1 ? await loadCluster() : void 0;
939
+ return runStart({
940
+ port,
941
+ host,
942
+ workers,
943
+ drainTimeoutMs: options.drainTimeoutMs ?? 3e5,
944
+ maxCallsPerWorker: options.maxCallsPerWorker ?? Number.POSITIVE_INFINITY
945
+ }, {
946
+ isWorker,
947
+ slot: () => ({
948
+ slot: Number(process.env[SLOT_ENV]),
949
+ slots: Number(process.env[SLOTS_ENV])
950
+ }),
951
+ load: () => loadProject(cwd),
952
+ build: ({ agent, env }) => buildProjectServer(cwd, agent, env, logger),
953
+ booted: () => tagged?.booted(),
954
+ readEnv: () => resolveServerEnv(cwd, void 0, DEPLOY_ENV_FILES),
955
+ assertBuilt: () => {
956
+ builtAgentPath(cwd);
957
+ },
958
+ startTracing,
959
+ cluster: () => {
960
+ if (!forking) throw new Error("node:cluster was not loaded: this process does not fork");
961
+ return nodeCluster(forking);
962
+ },
963
+ link: processLink,
964
+ listen: listenServer,
965
+ onSignal: (handler) => {
966
+ for (const signal of signals) process.on(signal, () => handler(signal));
967
+ },
968
+ ignoreSignals: () => {
969
+ for (const signal of signals) process.on(signal, () => void 0);
970
+ },
971
+ sleep,
972
+ exit: (code) => process.exit(code),
973
+ stop: stopProjectServer,
974
+ forever: () => new Promise(() => void 0),
975
+ ui: {
976
+ info: (message) => defaultUi.log.info(message),
977
+ error: (message) => defaultUi.log.error(message),
978
+ notify: (level, message) => defaultUi.notify(level, message)
179
979
  }
180
- };
980
+ });
181
981
  }
182
982
  //#endregion
183
983
  export { CLIENT_ARTIFACT_REL, DEFAULT_START_PORT, createProjectServer, executeStart, loadBuiltAgent };