@agimon-ai/po-cloudflare 0.0.2-alpha.76 → 0.0.2-alpha.78

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 (168) hide show
  1. package/dist/{approval-BlHIxC2J.js → approval-DRipNxVh.js} +4 -0
  2. package/dist/{approvalSession-UtzXVEB4.js → approvalSession-DPQQRkG4.js} +2 -2
  3. package/dist/assets/assets/{CodeEditorView-CaFk98Ji.js → CodeEditorView-CwDhkcuX.js} +2 -2
  4. package/dist/assets/assets/{abnfDiagram-WEYOIA3C-gzdpxFaJ.js → abnfDiagram-WEYOIA3C-x7ICShZ-.js} +2 -2
  5. package/dist/assets/assets/{architecture-WOLXFQ4H-TugrtWoO.js → architecture-WOLXFQ4H-BbNcuwIa.js} +1 -1
  6. package/dist/assets/assets/{architectureDiagram-ZHVYKT53-Xy_pnmaH.js → architectureDiagram-ZHVYKT53-BaKFNXDN.js} +2 -2
  7. package/dist/assets/assets/{blockDiagram-RJAE7QA3-pH1-jWYL.js → blockDiagram-RJAE7QA3-BpBDuUhc.js} +2 -2
  8. package/dist/assets/assets/{c4Diagram-XDPPPE54-CWmWk7y2.js → c4Diagram-XDPPPE54-CH1AYBxk.js} +2 -2
  9. package/dist/assets/assets/channel-DUu4-rZu.js +2 -0
  10. package/dist/assets/assets/{chunk-2E7WHVMD-C2O60zos.js → chunk-2E7WHVMD-zuvalEA0.js} +2 -2
  11. package/dist/assets/assets/{chunk-4EMNKR2T-CEHzGYY0.js → chunk-4EMNKR2T-Y1aujIa_.js} +2 -2
  12. package/dist/assets/assets/{chunk-55XCU76K-CjyzuqJm.js → chunk-55XCU76K-Cj_usw4a.js} +2 -2
  13. package/dist/assets/assets/{chunk-7S6XSTFO-Db8_vjDs.js → chunk-7S6XSTFO-CNv4j2oa.js} +2 -2
  14. package/dist/assets/assets/{chunk-AQDTSKZB-92c_fipW.js → chunk-AQDTSKZB-BgiafkbC.js} +2 -2
  15. package/dist/assets/assets/{chunk-DSNLSHJZ-DFGW_rzV.js → chunk-DSNLSHJZ-CEqk3yOv.js} +2 -2
  16. package/dist/assets/assets/{chunk-HAGFOTED-Cpx79XgA.js → chunk-HAGFOTED-w6XwPptZ.js} +2 -2
  17. package/dist/assets/assets/{chunk-HNE4Q36P-cz6K5cWs.js → chunk-HNE4Q36P-Du2F5NKF.js} +2 -2
  18. package/dist/assets/assets/{chunk-NQOKRVIF-Bhj8Cnrq.js → chunk-NQOKRVIF-e7LK2NBD.js} +2 -2
  19. package/dist/assets/assets/{chunk-UHW7PFBP-DugRZU3d.js → chunk-UHW7PFBP-CV1yEqMO.js} +2 -2
  20. package/dist/assets/assets/{chunk-VQ5W62QI-CFXU98Td.js → chunk-VQ5W62QI-Dz5nQ93K.js} +2 -2
  21. package/dist/assets/assets/{chunk-WQQL4CDK-BDYjxxgH.js → chunk-WQQL4CDK-CR_tliyN.js} +2 -2
  22. package/dist/assets/assets/chunk-XXDRQBXY-KxRgluI2.js +2 -0
  23. package/dist/assets/assets/{chunk-YZO67HFG-Bw3Zv3ms.js → chunk-YZO67HFG-DFykz1uM.js} +2 -2
  24. package/dist/assets/assets/{chunk-ZAUX2LTX-reWd5PI6.js → chunk-ZAUX2LTX-C-HZEj8t.js} +2 -2
  25. package/dist/assets/assets/{chunk-ZCHMQSOR-RCmNKJ0K.js → chunk-ZCHMQSOR-DhOusRJf.js} +2 -2
  26. package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DOBOI7kO.js → classDiagram-v2-4MYWR3UA-CODBKWcv.js} +2 -2
  27. package/dist/assets/assets/{cose-bilkent-JH36ORCC-Dnga9ThU.js → cose-bilkent-JH36ORCC-CQBDxRkG.js} +2 -2
  28. package/dist/assets/assets/{cynefin-EF2NZ3EQ-mbxppeTd.js → cynefin-EF2NZ3EQ-BqEZr_DI.js} +1 -1
  29. package/dist/assets/assets/{cynefinDiagram-WF24UDRP-D5uSCW7P.js → cynefinDiagram-WF24UDRP-CAFtVFnZ.js} +2 -2
  30. package/dist/assets/assets/{dagre-NK4GIZVX-D3Utujwv.js → dagre-NK4GIZVX-6EbIcHjw.js} +2 -2
  31. package/dist/assets/assets/{diagram-CBK3MWTC-Bg8QfzPb.js → diagram-CBK3MWTC-DxOPl4wX.js} +2 -2
  32. package/dist/assets/assets/{diagram-I5XIIV2D-NjETU96V.js → diagram-I5XIIV2D-Dn-nrQn0.js} +2 -2
  33. package/dist/assets/assets/{diagram-ODIL2UCW-BRY10xxY.js → diagram-ODIL2UCW-Df9GeJiZ.js} +2 -2
  34. package/dist/assets/assets/{diagram-PFBEJUXE-CO5Nfc2a.js → diagram-PFBEJUXE-CzsqYRcB.js} +2 -2
  35. package/dist/assets/assets/{diagram-RJA3I4VV-jxuLnXXk.js → diagram-RJA3I4VV-Chxf9kLz.js} +2 -2
  36. package/dist/assets/assets/{diagram-TYUNFSNR-B-dUsynt.js → diagram-TYUNFSNR-DsSL0naA.js} +2 -2
  37. package/dist/assets/assets/{dist-Bsp48Zck.js → dist-1eIdTf5S.js} +2 -2
  38. package/dist/assets/assets/{dist-JCg255PN.js → dist-B7Fq62ue.js} +2 -2
  39. package/dist/assets/assets/{dist-DtWJqHVb.js → dist-C-zBeZYG.js} +2 -2
  40. package/dist/assets/assets/{dist-BMmgMuDM.js → dist-CNPkFbM6.js} +2 -2
  41. package/dist/assets/assets/{dist-lOIB9DJk.js → dist-DHBIyPPx.js} +2 -2
  42. package/dist/assets/assets/{dist-9C1WeAys.js → dist-DR6uuD7b.js} +2 -2
  43. package/dist/assets/assets/{dist-C8son2cz.js → dist-Dul31jTx.js} +2 -2
  44. package/dist/assets/assets/{dist-CXebcDwS.js → dist-dedZfm22.js} +2 -2
  45. package/dist/assets/assets/{dist-CUuM0eUM.js → dist-zUhlfRuY.js} +2 -2
  46. package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-KNVNlIfc.js → ebnfDiagram-V4P3TTPT-fUIcNhqL.js} +2 -2
  47. package/dist/assets/assets/{elk-QONTBCTQ-DsX7hxD1.js → elk-QONTBCTQ-BtFtt9dx.js} +2 -2
  48. package/dist/assets/assets/{erDiagram-KYQIGQAA-pjQN44eX.js → erDiagram-KYQIGQAA-8nTQgw_u.js} +2 -2
  49. package/dist/assets/assets/{eventmodeling-K75KTNOO-BCKz9w4V.js → eventmodeling-K75KTNOO-u--ksfW0.js} +1 -1
  50. package/dist/assets/assets/flowDiagram-IUGLLWBU-U-4ltU4o.js +1 -0
  51. package/dist/assets/assets/{ganttDiagram-R7GPNTJY-CeuiGYpW.js → ganttDiagram-R7GPNTJY-CWqNS4bm.js} +2 -2
  52. package/dist/assets/assets/{gitGraph-VSP46ZUC-BsN0Vwsr.js → gitGraph-VSP46ZUC-Dy9xUPnQ.js} +1 -1
  53. package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-ZIMBu3bo.js → gitGraphDiagram-PDYL7XHY-D9OwLXxL.js} +2 -2
  54. package/dist/assets/assets/{index-fYkh5qQp.js → index-Blt5rLZT.js} +90 -90
  55. package/dist/assets/assets/{info-OHQRW6UA-CJmrVYr6.js → info-OHQRW6UA-ByFo5VxO.js} +1 -1
  56. package/dist/assets/assets/{infoDiagram-MVDRKAX5-BsAIEQmU.js → infoDiagram-MVDRKAX5-DkV7tUak.js} +2 -2
  57. package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-BX_86A9r.js → ishikawaDiagram-HPEHV2GE-D62xVlJr.js} +2 -2
  58. package/dist/assets/assets/{journeyDiagram-BOSHW7O7-DVGI0WoP.js → journeyDiagram-BOSHW7O7-CmGrCQyD.js} +2 -2
  59. package/dist/assets/assets/{kanban-definition-FNSA4HC5-4RLBwWbL.js → kanban-definition-FNSA4HC5-CQ-96zcl.js} +2 -2
  60. package/dist/assets/assets/{line-BL8hbik-.js → line-LyW2S8xe.js} +2 -2
  61. package/dist/assets/assets/{linear-BWVrkBYc.js → linear-Df5iFoGG.js} +2 -2
  62. package/dist/assets/assets/{mermaid-parser.core-CMk5l3Wp.js → mermaid-parser.core-DwGEOVKN.js} +4 -4
  63. package/dist/assets/assets/{mermaid.core-DZuf73R_.js → mermaid.core-UZa2JDq1.js} +5 -5
  64. package/dist/assets/assets/{mindmap-definition-6OY57UG3-CPuk1tgo.js → mindmap-definition-6OY57UG3-DXZpBkD7.js} +2 -2
  65. package/dist/assets/assets/{packet-JDAUHWVQ-pVue6YBL.js → packet-JDAUHWVQ-DVu5opyp.js} +1 -1
  66. package/dist/assets/assets/{pegDiagram-ECIUJNBX-B8Ly6ehm.js → pegDiagram-ECIUJNBX-D2PGrJQR.js} +2 -2
  67. package/dist/assets/assets/{pie-XZMESJXO-DXAHc3bX.js → pie-XZMESJXO-CoJXcSM1.js} +1 -1
  68. package/dist/assets/assets/{pieDiagram-GNMPY74T-9nVo6xZM.js → pieDiagram-GNMPY74T-DlPni3lE.js} +2 -2
  69. package/dist/assets/assets/{quadrantDiagram-D57K4MC3-DbBqshQw.js → quadrantDiagram-D57K4MC3-tDWbeX9Y.js} +2 -2
  70. package/dist/assets/assets/{radar-ABXABTNO-CKPxbvS6.js → radar-ABXABTNO-CiE-yXqS.js} +1 -1
  71. package/dist/assets/assets/{railroad-I3PHUGI6-CULlMjWr.js → railroad-I3PHUGI6-Bt5352hi.js} +1 -1
  72. package/dist/assets/assets/{railroad-abnf-LNEFI6M7-BRjXoZsa.js → railroad-abnf-LNEFI6M7-BJH5rnqj.js} +1 -1
  73. package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-CD_uPeUF.js → railroad-ebnf-DWYD2UWJ-C0KftBWL.js} +1 -1
  74. package/dist/assets/assets/{railroad-peg-JR7BVNR7-Cv-b3SRa.js → railroad-peg-JR7BVNR7-CRa7U91X.js} +1 -1
  75. package/dist/assets/assets/{railroadDiagram-Y72NRBL7-DJ77wAhA.js → railroadDiagram-Y72NRBL7-fOs3RTR8.js} +2 -2
  76. package/dist/assets/assets/{requirementDiagram-EQYSW5RA-R7PFvkp-.js → requirementDiagram-EQYSW5RA-SvE7rYXk.js} +2 -2
  77. package/dist/assets/assets/{sankeyDiagram-SY24JHO5-DR2gLc8z.js → sankeyDiagram-SY24JHO5-nqR9ZUs4.js} +2 -2
  78. package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-TwEQL0yK.js → sequenceDiagram-BLEHNHQU-CgEFMQSq.js} +2 -2
  79. package/dist/assets/assets/{src-Cv8dmcJt.js → src-B4g3Iold.js} +2 -2
  80. package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-ShloXczl.js → stateDiagram-v2-A6IESKWZ-C2jH_xDT.js} +2 -2
  81. package/dist/assets/assets/{swimlanes-B3ENRKFQ-D17E07lx.js → swimlanes-B3ENRKFQ-Dbf1mXvK.js} +2 -2
  82. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-Bc5KGsMc.js +9 -0
  83. package/dist/assets/assets/{timeline-definition-JXYKGLGB-BEvN2l_s.js → timeline-definition-JXYKGLGB-4u-pC3xz.js} +2 -2
  84. package/dist/assets/assets/{treeView-D4JQ5SDB-B0QcYOKz.js → treeView-D4JQ5SDB-CZmVi5-J.js} +1 -1
  85. package/dist/assets/assets/{treemap-SAJKECNS-CIGIJniE.js → treemap-SAJKECNS-BajhrENS.js} +1 -1
  86. package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-DbS-GLv8.js → usecaseDiagram-WPOLBNNX-J1gh4d5h.js} +2 -2
  87. package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-CEkmUNoT.js → vennDiagram-Q3Y3IDCW-CIRtS6C5.js} +2 -2
  88. package/dist/assets/assets/{wardley-7MLQ67FV-D9b-h7oE.js → wardley-7MLQ67FV-DjBwbtAb.js} +1 -1
  89. package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-BoWIYn_M.js → wardleyDiagram-IVAIDKWA-Cui7ZUN1.js} +2 -2
  90. package/dist/assets/assets/{webpack-rEg3nylj.js → webpack-FJjN4adW.js} +2 -2
  91. package/dist/assets/assets/{xychartDiagram-4URNHDU4-xJdWE_nx.js → xychartDiagram-4URNHDU4-I-UzMoDZ.js} +2 -2
  92. package/dist/assets/bundle-asset-policy.json +1 -1
  93. package/dist/assets/index.html +1 -1
  94. package/dist/assets/plugins/chunks/po-web-runtime-C0B3uAoC.js +1 -0
  95. package/dist/assets/plugins/compositions.json +1 -1
  96. package/dist/assets/plugins/slots/{approval.09e72f36-B4Y8Wjzl.js → approval.dd60ec90-gfcirIrD.js} +1 -1
  97. package/dist/assets/plugins/slots/{artifacts.50b639bb-5Kf50LM1.js → artifacts.a078f1a5-B5YmdqFC.js} +1 -1
  98. package/dist/assets/plugins/slots/{author.ea449ace-BUAjd0RY.js → author.b2063a1b-QDThbn6B.js} +3 -3
  99. package/dist/assets/plugins/slots/{autocompact.6f428144-DUwf4L4s.js → autocompact.86aeccf4-DxTuE9o-.js} +1 -1
  100. package/dist/assets/plugins/slots/{backdrop-bamboo.6e4c928d-CT9PXrny.js → backdrop-bamboo.1a7d88ef-BfruoASs.js} +1 -1
  101. package/dist/assets/plugins/slots/{browse.fa1f1a50-ClrBioNv.js → browse.4b750f64-LwBuFuNb.js} +1 -1
  102. package/dist/assets/plugins/slots/{builtin-tools.75108f21-DmtavYBT.js → builtin-tools.0a7f0b8e-Cy2eN76-.js} +1 -1
  103. package/dist/assets/plugins/slots/{calendar.d8b70190-DmudDrcG.js → calendar.76ad65fa-CihobxD6.js} +1 -1
  104. package/dist/assets/plugins/slots/{codemode.c58fb583-BkVR1X2Y.js → codemode.ff16ac06-Dbjm7Efq.js} +1 -1
  105. package/dist/assets/plugins/slots/{domain.753f9f92-Bv-dlY79.js → domain.3ddea842-CJa-EzBA.js} +1 -1
  106. package/dist/assets/plugins/slots/{edit.804fec90-mJXCIk4G.js → edit.c5b0b072-Bp0bQ3N2.js} +1 -1
  107. package/dist/assets/plugins/slots/{files.66ffc636-CCRW8t1-.js → files.8ffcdcc0-re8nr2oz.js} +1 -1
  108. package/dist/assets/plugins/slots/{goal.45dffa01-q_Zh5QxW.js → goal.4524e2bf-C5mGe79a.js} +1 -1
  109. package/dist/assets/plugins/slots/{grep.98262cff-CTDwtVaK.js → grep.95f470b3-ClgsMgtm.js} +1 -1
  110. package/dist/assets/plugins/slots/{help.5fbd20f7-BBw7NYJI.js → help.dfbc8216-BGywkUKZ.js} +1 -1
  111. package/dist/assets/plugins/slots/{log.cb964209-BLY7IzD1.js → log.19bda339-6jMYUtlN.js} +1 -1
  112. package/dist/assets/plugins/slots/{mcp.82cc1ff5-5yoTabz8.js → mcp.ffbe405a-BnDP_LDU.js} +1 -1
  113. package/dist/assets/plugins/slots/{plan.3852ba52-DmdaEVVw.js → plan.2879a6ae-BXxVUfMI.js} +1 -1
  114. package/dist/assets/plugins/slots/{profile.ab16dcec-DOw3MhWl.js → profile.176710dd-Bc4Rwfhz.js} +1 -1
  115. package/dist/assets/plugins/slots/{prompts.ae48c07a-DQVmTxFZ.js → prompts.2c187969-CIBsOkp9.js} +1 -1
  116. package/dist/assets/plugins/slots/{read.4560591a-Bun0fKn1.js → read.1629d556-D-NY0ZCv.js} +1 -1
  117. package/dist/assets/plugins/slots/{runner.6e494d59-BDtBIqmQ.js → runner.962030e5-CCUVliK7.js} +1 -1
  118. package/dist/assets/plugins/slots/{scaffold.d87a6ee0-DZOiNwOS.js → scaffold.14b5f76b-DW44NU9X.js} +1 -1
  119. package/dist/assets/plugins/slots/{session-mcp.2be84084-DQpF2DkA.js → session-mcp.51089b63-Im-iuHcn.js} +1 -1
  120. package/dist/assets/plugins/slots/{sessions.6f47cb4c-y61JDvak.js → sessions.fc763f42-CL0PHuD4.js} +1 -1
  121. package/dist/assets/plugins/slots/{skill.62a0a1b3-C-mkriRv.js → skill.f5396fde-DHDfhNXW.js} +1 -1
  122. package/dist/assets/plugins/slots/{space.65a27e5a-Cr1HSI_z.js → space.d7bddb51-DFHblvL5.js} +1 -1
  123. package/dist/assets/plugins/slots/{subagents.8bb9992c-CrpR1Jhi.js → subagents.24539507-Db6YnHJd.js} +1 -1
  124. package/dist/assets/plugins/slots/{template-advanced.59f3f98a-CSuMHJ9x.js → template-advanced.292533fb-DyvcGxNV.js} +1 -1
  125. package/dist/assets/plugins/slots/{template-desktop.0f0b8491-C2ZheI0_.js → template-desktop.a1ef756c-5EQH-r7P.js} +1 -1
  126. package/dist/assets/plugins/slots/{template-elegant.0e3b0acf-Cq5Y_6VL.js → template-elegant.ceb23ac7-CrmEUE6V.js} +1 -1
  127. package/dist/assets/plugins/slots/{vault.3cbfcdc3-ZKO66wy8.js → vault.57fd9047-9cm8PfeP.js} +1 -1
  128. package/dist/assets/plugins/slots/{voice.a952113d-CsdoPA4G.js → voice.76006b18-BSC2gHHY.js} +1 -1
  129. package/dist/assets/plugins/slots/{web-search.65013836-C7W5RyLj.js → web-search.b025dda1-BMe5RM8K.js} +1 -1
  130. package/dist/assets/plugins/slots/{workflows.cbc5c5c0-BLNlHcfa.js → workflows.1fd6a554-CzFPuLnU.js} +1 -1
  131. package/dist/browser-BYWSPAEE.js +897 -0
  132. package/dist/{exports-Ct56PRB9.js → exports-BnHiOfC6.js} +1 -1
  133. package/dist/{index.edge-BRaAhap2.js → index.edge-By7eSfpp.js} +2 -2
  134. package/dist/sealedChannel-BeWNTWys.js +27 -0
  135. package/dist/{server-B3U0W7zD.js → server-1yS_uE-G.js} +1 -1
  136. package/dist/{server-CcKKktvn.js → server-B1kdSQrK.js} +1 -1
  137. package/dist/{server-fYfb0gN8.js → server-B3tod9fX.js} +3 -3
  138. package/dist/{server-BlbuM_IJ.js → server-BCuQ5v6n.js} +2 -2
  139. package/dist/{server-DAFM6HnJ.js → server-BGHoSIRR.js} +3 -3
  140. package/dist/{server-BUBijhBb.js → server-BN4AdrfM.js} +3 -3
  141. package/dist/{server-BSpJMYLb.js → server-Bl6gkrM7.js} +1 -1
  142. package/dist/{server-BPS6xFya.js → server-Bp5B4707.js} +1 -1
  143. package/dist/{server-D6-_DT9g.js → server-C-LM-7Mp.js} +1 -1
  144. package/dist/{server-CaFzaibK.js → server-Ca3X3h6Q.js} +1 -1
  145. package/dist/{server-CLRgSPVY.js → server-Cdrr9D-D.js} +1 -1
  146. package/dist/{server-BJssIIpm.js → server-Cj-2V-Z6.js} +1 -1
  147. package/dist/{server-Dnvp2U6V.js → server-CkEwZP4t.js} +1 -1
  148. package/dist/{server-DPG7BH6w.js → server-CodZPkK3.js} +1 -1
  149. package/dist/{server-7-DnO2Ww.js → server-CuKy4B95.js} +230 -117
  150. package/dist/{server-Dl3sng3O.js → server-D467psm_.js} +1 -1
  151. package/dist/{server-BUgDdcRW.js → server-DHAcLeIr.js} +1 -1
  152. package/dist/{server-HIbQWBba.js → server-DLZgrjI9.js} +9 -7
  153. package/dist/{server-BeAYfrzJ.js → server-DqEJjOJZ.js} +1 -1
  154. package/dist/{server-CKQwNrO8.js → server-DvXlixQN.js} +1 -1
  155. package/dist/{server-CMov-S5-.js → server-EyLWvUXw.js} +1 -1
  156. package/dist/{server-DMbdJzSQ.js → server-RF5gqssS.js} +1 -1
  157. package/dist/{server-BLcw1z6S.js → server-pp-NQWAR.js} +1 -1
  158. package/dist/{server-BqvkcVLn.js → server-rKR_yimq.js} +1 -1
  159. package/dist/{server-OzzJbeaS.js → server-sbfI6TAL.js} +2 -2
  160. package/dist/{type-DppaYz6F.js → type-1FxIJmfz.js} +2 -26
  161. package/dist/worker.js +80525 -80817
  162. package/package.json +49 -49
  163. package/dist/assets/assets/channel-CJxh7kPr.js +0 -2
  164. package/dist/assets/assets/chunk-XXDRQBXY-B7vCmBOn.js +0 -2
  165. package/dist/assets/assets/flowDiagram-IUGLLWBU-BU7xmb8h.js +0 -1
  166. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-i6-zDqZm.js +0 -9
  167. package/dist/assets/plugins/chunks/po-web-runtime-CQ9hLtG-.js +0 -1
  168. package/dist/browser-ks_k-6KA.js +0 -36
@@ -1 +1 @@
1
- import{$r as e,At as t,Ba as n,Cn as r,Da as i,Ft as a,Gi as o,Ht as s,In as c,It as l,Ka as u,Ki as d,Kt as f,Lt as p,Ma as m,Mi as h,Mn as g,Mt as _,Na as v,Nn as y,Pa as b,Pi as x,Pn as S,Pr as C,Pt as w,Ra as ee,Ta as T,Un as E,Wa as D,Wi as O,Wn as k,Xi as te,Yi as ne,Zi as re,_n as ie,cn as ae,cr as A,ea as oe,eo as j,gn as se,hn as ce,ii as le,ja as ue,mn as de,na as fe,qa as pe,qi as me,qt as M,vi as he,vn as ge,wa as _e,wi as ve,yn as ye}from"../chunks/po-web-runtime-CQ9hLtG-.js";var be=`x-po-client-metadata`,xe=`poClient`,Se=64;function Ce(e){return typeof e==`string`&&/^[A-Za-z0-9_-]{1,64}$/u.test(e)}function we(e){if(typeof e!=`string`)return;let t=e.replaceAll(/[\p{Cc}\p{Cf}]/gu,``).trim(),n=Array.from(t).length;return n>=1&&n<=Se?t:void 0}function Te(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ee(e){if(!Te(e))return{status:`invalid`};if(Number.isSafeInteger(e.version)&&e.version!==1)return{status:`unsupported`};let t=we(e.deviceName);if(e.version!==1||!Ce(e.deviceId)||e.instanceId!==void 0&&!Ce(e.instanceId)||typeof e.clientKind!=`string`||![`web`,`desktop`,`ios`,`android`].includes(e.clientKind)||t===void 0||!Number.isSafeInteger(e.nameUpdatedAt)||typeof e.nameUpdatedAt!=`number`||e.nameUpdatedAt<0)return{status:`invalid`};for(let t of[`browser`,`platform`])if(e[t]!==void 0&&(we(e[t])===void 0||we(e[t])!==e[t]))return{status:`invalid`};return{status:`ok`,metadata:{version:1,deviceId:e.deviceId,...e.instanceId===void 0?{}:{instanceId:e.instanceId},clientKind:e.clientKind,deviceName:t,nameUpdatedAt:e.nameUpdatedAt,...e.browser===void 0?{}:{browser:e.browser},...e.platform===void 0?{}:{platform:e.platform}}}}function De(e){let t=new TextEncoder().encode(JSON.stringify(e));return btoa(String.fromCharCode(...t)).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)}function Oe(e){let t=Ee(e);if(t.status!==`ok`)throw Error(`Invalid Po client metadata`);let n=De(t.metadata);if(n.length>2048)throw Error(`Po client metadata exceeds encoded limit`);return n}function ke(e){try{if(`preface`in e)return!Te(e.preface)||!Object.hasOwn(e.preface,`poClient`)?{status:`absent`}:Object.keys(e.preface).length!==1||De(e.preface.poClient).length>2048?{status:`invalid`}:Ee(e.preface.poClient);let t;if(`query`in e){let n=e.query.getAll(xe);if(n.length>1)return{status:`invalid`};t=n[0]}else t=e.header;if(t==null)return{status:`absent`};if(t.length>2048||!/^[A-Za-z0-9_-]+$/u.test(t))return{status:`invalid`};let n=atob(t.replaceAll(`-`,`+`).replaceAll(`_`,`/`)),r=Uint8Array.from(n,e=>e.charCodeAt(0)),i=new TextDecoder(`utf-8`,{fatal:!0}).decode(r);return btoa(n).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)===t?Ee(JSON.parse(i)):{status:`invalid`}}catch{return{status:`invalid`}}}var N=16e3,Ae=`application/vnd.po.pcm-s16le`,je=`x-po-voice-activity-state`,Me=`x-po-voice-activity-level`,Ne=`x-po-voice-activity-elapsed`,Pe=`x-po-voice-activity-epoch`,Fe=`x-po-voice-activity-speech-ms`,Ie=`x-po-voice-activity-echo-speech-ms`,Le=`voice_media_wake`,P={clientConnect:`/client/connect`,clientDisconnect:`/client/disconnect`,clientEvents:`/client/events`,clientHeartbeat:`/client/heartbeat`,clientAudio:`/client/audio`,clientCaptureStopped:`/client/capture-stopped`,clientPlaybackAudio:`/client/playback-audio`,clientPlaybackResult:`/client/playback-result`,hostCaptureStart:`/host/capture/start`,hostCaptureAudio:`/host/capture/audio`,hostCaptureStop:`/host/capture/stop`,hostCaptureAbort:`/host/capture/abort`,hostPlaybackStart:`/host/playback/start`,hostPlaybackAudio:`/host/playback/audio`,hostPlaybackAudioEnd:`/host/playback/audio-end`,hostPlaybackResult:`/host/playback/result`,hostPlaybackStop:`/host/playback/stop`,hostPlaybackAbort:`/host/playback/abort`},F={audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1};function Re(e){return{...F,audio:{...F.audio,deviceId:{exact:e}}}}function ze(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e;return Object.keys(t).some(e=>![`deviceId`,`eventEpoch`,`sequence`].includes(e))||t.deviceId!==void 0&&!Ce(t.deviceId)||typeof t.eventEpoch!=`string`||t.eventEpoch.length===0||t.eventEpoch.length>200||!Number.isSafeInteger(t.sequence)||t.sequence<0?null:{eventEpoch:t.eventEpoch,sequence:t.sequence,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}}function Be(e,t,n,r,i,a){let o=()=>{let i=e.select(e.store.state,t);return i?.eventEpoch===n&&i.sequence>r?i:void 0},s=o();return s!==void 0||a.aborted?Promise.resolve(s):new Promise(t=>{let n=!1,r,s,c=e=>{n||(n=!0,r!==void 0&&clearTimeout(r),a.removeEventListener(`abort`,l),s?.unsubscribe(),t(e))},l=()=>c();if(s=e.store.subscribe(()=>{let e=o();e!==void 0&&c(e)}),a.addEventListener(`abort`,l,{once:!0}),a.aborted){c();return}r=setTimeout(()=>c(),i);let u=o();u!==void 0&&c(u)})}function Ve(e,t){let n=ke({header:t});return n.status===`ok`&&n.metadata.deviceId===e}var He=`voice_ownership`,Ue=/^[A-Za-z0-9._:-]+$/u;function We(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Ge(e,t){return Object.keys(e).every(e=>t.includes(e))}function Ke(e,t=128){return typeof e==`string`&&e.length>0&&e.length<=t&&Ue.test(e)}function qe(e){return Ke(e,200)||typeof e==`string`&&/^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e)}function Je(e){let t=We(e);if(t!==void 0&&Ge(t,[`type`,`version`,`deviceId`,`activeSessionId`,`handoff`])&&t.type===`browser-media-session`&&Ce(t.deviceId)&&t.version===5&&(t.activeSessionId===null||qe(t.activeSessionId))){if(t.handoff!==void 0){let e=We(t.handoff);if(e===void 0||!Ge(e,[`id`,`phase`,`sourceSessionId`,`targetSessionId`])||!Ke(e.id)||![`preparing`,`rebinding`,`failed`].includes(e.phase)||!qe(e.sourceSessionId)||e.targetSessionId!==void 0&&!qe(e.targetSessionId)||e.phase===`rebinding`&&e.targetSessionId===void 0)return}return t}}var Ye=4,Xe=Symbol.for(`@agimon-ai/po-voice:web-media-page-state.v4`);function Ze(){return{version:Ye,wakes:ee(void 0),activeSession:m(null),handoff:m(void 0),browserState:m(void 0),realtimeControls:m(void 0),switchPending:m(void 0),runtime:m(void 0)}}function Qe(){let e=globalThis,t=e[Xe];if(t?.version===Ye)return t;let n=Ze();return e[Xe]=n,n}var I=Qe(),$e=I.wakes,L=I.activeSession,et=I.handoff,R=I.browserState,tt=I.runtime,nt=I.switchPending,z=I.realtimeControls,rt={subscribe(e){let t=[R,L,nt].map(t=>t.store.subscribe(e));return()=>{for(let e of t)e.unsubscribe()}},isActive(e){let t=R.store.state,n=t?.sessionId===null&&t.realtime!==void 0&&t.realtime.connection!==`closed`,r=e!==null&&nt.store.state?.sessionId===e;return n||L.store.state!==null||r}},it={subscribe(e){let t=R.store.subscribe(e);return()=>t.unsubscribe()},isActive(){let e=R.store.state;return e?.sessionId===null&&e.realtime!==void 0&&e.realtime.connection!==`closed`}},at={channel:Le,parse:ze,apply(e,t){Ve(t.deviceId,_())&&$e.update(e,e=>e?.eventEpoch===t.eventEpoch&&t.sequence<=e.sequence?e:t)},drop(e){$e.drop(e)}},ot={channel:He,parse(e){return Je(e)??null},apply(e,t){Ve(t.deviceId,_())&&(et.update(()=>t.handoff),L.update(e=>e===t.activeSessionId?e:t.activeSessionId))},drop(e){et.store.state===void 0&&L.update(t=>t===e?null:t)}};function st(e,t,n,r,i){return Be($e,e,t,n,r,i)}var ct=`/manual/transcribe`,lt=`x-po-audio-duration-ms`,ut=3e5,dt={sdpBytes:65536,eventBytes:65536,instructionsCharacters:16384,textCharacters:8192,identifierCharacters:256,pendingRequests:1,retainedRequests:128},ft=new Set([`session.started`,`session.updated`,`input_transcript.added`,`output_transcript.added`,`turn.done`,`delegation.created`]),B={hostStart:`/host/realtime/start`,hostStop:`/host/realtime/stop`,hostPoll:`/host/realtime/poll`,hostSend:`/host/realtime/send`,hostControl:`/host/realtime/control`,clientNegotiate:`/client/realtime/negotiate`,clientEvent:`/client/realtime/event`,clientState:`/client/realtime/state`},pt={status:{method:`GET`,path:`/status`,response:void 0},control:{method:`POST`,path:`/control`,response:void 0},readiness:{method:`GET`,path:`/readiness`,response:void 0},liveStatus:{method:`GET`,path:`/live/status`,response:void 0},liveControl:{method:`POST`,path:`/live/control`,response:void 0},relayBinding:{method:`POST`,path:`/relay-binding`,response:void 0},relay:{method:`POST`,path:`/relay`,query:[`binding`],response:void 0},clientConnect:{method:`POST`,path:P.clientConnect,response:void 0},clientDisconnect:{method:`POST`,path:P.clientDisconnect},clientHeartbeat:{method:`POST`,path:P.clientHeartbeat,response:void 0},clientEvents:{method:`GET`,path:P.clientEvents,query:[`clientId`,`connectionId`,`after`,`wait`],response:void 0},clientAudio:{method:`POST`,path:P.clientAudio,query:[`clientId`,`connectionId`,`captureId`]},clientCaptureStopped:{method:`POST`,path:P.clientCaptureStopped},clientPlaybackAudio:{method:`GET`,path:P.clientPlaybackAudio,query:[`clientId`,`connectionId`,`playbackId`,`wait`]},clientPlaybackResult:{method:`POST`,path:P.clientPlaybackResult},realtimeNegotiate:{method:`POST`,path:B.clientNegotiate,response:void 0},realtimeEvent:{method:`POST`,path:B.clientEvent},realtimeState:{method:`POST`,path:B.clientState},manualTranscribe:{method:`POST`,path:ct,response:void 0}},V=_e(pt,{scopes:[`host`,`workspace`,`session`],basePath:`voice`,transport:(e,n)=>t.fetch(e,n),sessionAddress:j}),H=_e(pt,{scopes:[`host`,`workspace`,`session`],basePath:`voice-media`,transport:(e,n)=>t.fetch(e,n),sessionAddress:j}),mt=/^[⠀-⣿]\s*/u,ht=`voice auto:`,gt=`voice live:`,_t=`voice:`,vt=/\b(\d+:[0-5]\d)\b/u,yt={mode:`off`,phase:`idle`,label:`not listening`,detail:`start autonomous capture from the modes, or dictate one message with the voice tool.`,tone:`idle`,active:!1,microphoneMuted:!1,elapsed:``},bt=[{match:`sending composed prompt`,phase:`sending`,label:`sending draft`,detail:`handing the complete composed prompt to Pi.`,tone:`live`},{match:`composing`,phase:`composing`,label:`composing prompt`,detail:`speech segments are buffered until you say Po send or Po cancel.`,tone:`attention`},{match:`hearing speech`,phase:`hearing`,label:`hearing you`,detail:`speech detected; it will transcribe when you pause.`,tone:`live`},{match:`processing while listening`,phase:`processing`,label:`transcribing`,detail:`still listening while it works out what you said.`,tone:`live`},{match:`narrating`,phase:`narrating`,label:`narrating`,detail:`reading the reply aloud.`,tone:`live`},{match:`microphone muted`,phase:`muted`,label:`microphone muted`,detail:`narration remains active; unmute to start a fresh capture.`,tone:`idle`},{match:`confirmation needed`,phase:`confirming`,label:`needs confirmation`,detail:`it is waiting on an answer before it acts.`,tone:`attention`},{match:`waiting for keyboard input`,phase:`waiting`,label:`waiting for the keyboard`,detail:`something asked for typed input, so capture is paused.`,tone:`attention`},{match:`draining`,phase:`draining`,label:`stopping`,detail:`finishing what it already heard.`,tone:`attention`},{match:`starting`,phase:`starting`,label:`starting`,detail:`preparing autonomous microphone capture.`,tone:`live`},{match:`listening`,phase:`listening`,label:`listening`,detail:``,tone:`live`}];function xt(e){let t=(e??``).replace(mt,``).trim();if(t===``)return yt;if(t.startsWith(ht)){let e=t.slice(11).trim(),n=e.includes(`microphone muted`),r=bt.find(t=>e.includes(t.match));return r?{mode:`auto`,phase:r.phase,label:r.label,detail:r.detail,tone:r.tone,active:r.phase!==`muted`,microphoneMuted:n,elapsed:``}:{...yt,mode:`auto`,label:e||`listening`,detail:``,tone:`live`,active:!0,microphoneMuted:n}}if(t.startsWith(gt))return{mode:`live`,phase:`listening`,label:`talking`,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``};if(t.startsWith(_t)){let e=t.slice(6).trim(),n=e.startsWith(`recording`);return{mode:`manual`,phase:n?`recording`:`transcribing`,label:n?`recording`:`transcribing`,detail:n?`the microphone is open; it sends when you stop.`:`turning what you said into text.`,tone:n?`attention`:`live`,active:!0,microphoneMuted:!1,elapsed:n?vt.exec(e)?.[1]??``:``}}return{mode:`auto`,phase:`listening`,label:t,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``}}function St({state:t,takeOver:n,retry:r,mute:i,end:a,pending:o,error:s}){let c=t.kind===`deviceLive`,u=t.kind===`standby`,d=t.ownerName??`another device`;return p(`section`,{"aria-label":`Voice`,className:`flex flex-col gap-3`,children:[l(`h3`,{className:`text-lg font-semibold text-po-hi`,children:`Voice`}),p(`div`,{className:`flex items-center gap-2`,children:[l(oe,{tone:c?`cyan`:u?`muted`:`magenta`}),l(`span`,{className:`text-base font-semibold text-po-hi`,children:u?`Voice is on standby`:c?`Live on this device`:`Voice is active on ${d}`})]}),l(`p`,{className:`text-sm leading-relaxed text-po-dim`,children:u?`Another window on this device is using voice. This window is not listening.`:c?`${t.deviceName??`This device`} · Microphone live. Other devices can run their own Live conversations separately.`:t.kind===`stale`?`Voice moved since you last checked. Take over from ${d} whenever you are ready.`:`This device is not listening. You can move this session’s voice here whenever you are ready.`}),t.kind===`conflict`||t.kind===`stale`?l(`div`,{children:l(e,{variant:`secondary`,disabled:o||!n,onClick:n,children:`Take over`})}):c?p(`div`,{className:`flex gap-2`,children:[l(e,{variant:`subtle`,disabled:o||!i,onClick:i,children:`Mute`}),l(e,{variant:`subtle`,disabled:o||!a,onClick:a,children:`End Live on this device`})]}):null,c?l(`p`,{className:`text-sm text-po-dim`,children:`Each device’s Live conversation is billed separately.`}):null,s?l(`p`,{role:`alert`,className:`text-sm text-po-red`,children:s}):null,s&&r?l(`div`,{children:l(e,{variant:`subtle`,disabled:o,onClick:r,children:`Try again`})}):null]})}var Ct={idle:`muted`,live:`cyan`,attention:`yellow`},wt={idle:`text-po-dim`,live:`text-po-cyan`,attention:`text-po-yellow`};function Tt({tone:e}){return l(`span`,{"aria-hidden":!0,className:`flex h-3 items-end gap-[2px]`,children:[3,7,5,9,4].map((t,n)=>l(`span`,{className:`w-[2px] animate-pulse rounded-xs ${e===`attention`?`bg-po-yellow`:`bg-po-cyan`}`,style:{height:`${String(t)}px`,animationDelay:`${String(n*120)}ms`}},n))})}function U({label:t,onClick:n,pending:r,...i}){return n===void 0?null:l(e,{variant:`subtle`,size:`xs`,disabled:r,onClick:n,...i,children:t})}function Et(e,t){return e===void 0?``:t?`output interrupted locally and will stay silent until this realtime session ends.`:e.error?e.error:e.speaking?`assistant speaking`:e.muted?`microphone muted`:e.listening?`microphone live`:`establishing secure media`}function Dt(e){switch(e.kind){case`switching`:return{phase:`switching`,tone:`live`,pulse:!0,label:`switching to ${e.mode===`live`?`live conversation`:`daily work`}`,detail:e.mode===`live`?`daily work stopped listening. Live opens the microphone once it connects.`:`live has ended. Daily work starts listening in a moment.`,meter:!1};case`conflict`:return{phase:`conflict`,tone:`attention`,pulse:!1,label:`microphone unavailable`,detail:`another Po window (the desktop app or a browser tab) is using the microphone. Close that window to use it here.`,meter:!1};case`daily`:return{phase:e.view.phase,tone:e.view.tone,pulse:e.view.active,label:e.view.label,detail:e.view.detail||(e.view.phase===`listening`&&!e.signInHint?`speak whenever you are ready`:``),meter:e.view.active};case`live`:{let t=e.realtime?.connection??`connected`,n=t===`connected`;return{phase:`realtime-${t}`,tone:n?`live`:`attention`,pulse:n,label:n?`talking`:`connecting live conversation`,detail:Et(e.realtime,e.interrupted),meter:n&&e.realtime!==void 0&&!e.realtime.muted}}case`live-failed`:return{phase:`realtime-failed`,tone:`attention`,pulse:!1,label:`live could not connect`,detail:e.error,meter:!1};case`live-elsewhere`:return{phase:`live-elsewhere`,tone:`idle`,pulse:!1,label:`live is talking in another session`,detail:``,meter:!1};case`daily-elsewhere`:return{phase:`daily-elsewhere`,tone:`idle`,pulse:!1,label:`daily work is listening in another session`,detail:``,meter:!1};case`manual`:case`idle`:return{phase:e.view.phase,tone:e.view.tone,pulse:e.view.active,label:e.view.label,detail:e.view.detail,meter:e.view.active,elapsed:e.view.elapsed}}}function Ot({state:t,picker:n,actions:r,pending:i,error:a,ownership:o,ownershipActions:s}){if(o)return l(St,{state:o,takeOver:s?.takeOver,retry:s?.retry,mute:r.mute,end:r.end,pending:i,error:a});let c=Dt(t),u=t.kind===`daily`&&t.view.microphoneMuted,d=t.kind===`live`&&t.realtime?.muted===!0,f=u||d?`unmute`:`mute`,m=t.kind===`live-failed`,h=t.kind===`daily`&&t.signInHint;return p(`div`,{"data-testid":`voice-activity`,"data-voice-phase":c.phase,className:`flex flex-col gap-2 px-1`,children:[n===void 0?null:p(E,{"aria-label":`Voice for this session`,value:n.value,disabled:n.disabled||i,onValueChange:e=>n.onPick(e),className:`grid grid-cols-2 gap-1.5`,children:[l(k,{value:`live`,"data-testid":`voice-pick-live`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Live`}),l(k,{value:`legacy`,"data-testid":`voice-pick-legacy`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Daily work`})]}),p(`span`,{className:`flex min-w-0 items-center gap-2`,children:[l(oe,{tone:Ct[c.tone],pulse:c.pulse}),l(`span`,{"data-testid":`voice-label`,className:`flex-1 truncate text-base font-semibold ${wt[c.tone]}`,children:c.label}),c.elapsed?l(`span`,{"data-testid":`voice-elapsed`,className:`shrink-0 text-sm tabular-nums text-po-yellow`,children:c.elapsed}):null,c.meter?l(Tt,{tone:c.tone}):null]}),t.kind===`daily`||t.kind===`live`?p(`span`,{className:`flex flex-wrap gap-1.5`,children:[l(U,{label:f,onClick:r.mute,pending:i,"aria-pressed":u||d,...t.kind===`daily`?{"data-testid":`voice-autonomous-microphone-toggle`,"aria-label":`${f} autonomous voice microphone`,title:`${f} autonomous voice microphone`}:{}}),l(U,{label:`interrupt`,onClick:t.kind===`live`?r.interrupt:void 0,pending:i,title:`Interrupt local output. Output stays silent until this realtime session ends.`}),l(U,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,c.detail&&!h?l(`span`,{"data-testid":`voice-detail`,role:m?`alert`:void 0,className:`text-sm leading-relaxed text-po-dim`,children:m&&r.useDailyWork!==void 0?`${c.detail} You can keep talking with daily work.`:c.detail}):null,h?p(`span`,{className:`flex flex-col items-start gap-2`,children:[l(`span`,{"data-testid":`voice-sign-in-hint`,className:`text-sm leading-relaxed text-po-dim`,children:`live needs your ChatGPT for Po features sign-in. Daily work keeps listening meanwhile.`}),r.signIn===void 0?null:l(e,{variant:`secondary`,size:`xs`,"data-testid":`voice-sign-in`,onClick:r.signIn,children:`sign in`})]}):null,m?p(`span`,{className:`flex flex-wrap gap-1.5`,children:[l(U,{label:`use daily work`,onClick:r.useDailyWork,pending:i,"data-testid":`voice-use-daily`}),l(U,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,t.kind===`live-elsewhere`||t.kind===`daily-elsewhere`?l(`span`,{className:`flex`,children:l(U,{label:t.kind===`live-elsewhere`?`move Live here`:`move daily work here`,onClick:t.kind===`live-elsewhere`?r.routeLiveHere:r.moveDailyWorkHere,pending:i,"data-testid":t.kind===`live-elsewhere`?`voice-global-live-transfer`:`voice-daily-move`})}):null,a===null?null:l(`span`,{role:`alert`,className:`text-sm leading-relaxed text-po-yellow`,children:a})]})}function kt(e){return e instanceof Error?e.message:String(e)}function At({sessionId:e,statuses:t,openSettings:n,registeredModes:r}){let i=xt(t[`po-voice`]),a=w(R.store),o=w(z.store),c=w(L.store),u=w(nt.store),[d,f]=M(!1),[p,m]=M(null),[h,g]=M(!1),[_,v]=M(),y=r?.includes(`voice-auto`)===!0;s(()=>{if(e===null||!y)return;let t=!1;return V.session(e).status().then(n=>{!t&&n.ok&&v({sessionId:e,realtime:n.data.media.realtime})}).catch(()=>{t||v({sessionId:e,realtime:!1})}),()=>{t=!0}},[y,e]);let b=e===null||(_?.sessionId===e?_.realtime:a?.realtime!==void 0||i.mode===`live`||u?.sessionId===e&&u?.mode===`live`),x=e!==null&&a?.sessionId===e?a.realtime:void 0,S=a?.sessionId===null?a.realtime:void 0,C=x??S,ee=C!==void 0&&C.connection!==`closed`,T=o?.sessionId===null||o?.sessionId===e?o:void 0,E=e!==null&&u?.sessionId===e?{kind:`switching`,mode:u.mode}:e!==null&&a?.sessionId===e&&a.phase===`conflict`&&i.mode!==`off`?{kind:`conflict`}:i.mode===`auto`?{kind:`daily`,view:i,signInHint:h}:C?.connection===`failed`&&i.mode!==`manual`?{kind:`live-failed`,error:C.error??`the live provider did not answer.`}:e!==null&&i.mode!==`live`&&x===void 0&&S?.connection===`connected`?{kind:`live-elsewhere`}:i.mode===`live`||ee?{kind:`live`,...C===void 0?{}:{realtime:C},interrupted:a?.realtimeOutputInterrupted===!0}:c!==null&&c!==e&&i.mode===`off`?{kind:`daily-elsewhere`}:i.mode===`manual`?{kind:`manual`,view:i}:{kind:`idle`,view:i},D=async e=>{if(!d){f(!0),m(null);try{await e()}catch(e){m(kt(e))}finally{f(!1)}}},O=async(t,n,r,i)=>{if(e===null)throw Error(`Voice controls need a session.`);if((t===`activate`||t===`switch`)&&n!==`live`){let a=tt.store.state;if(!a)throw Error(`Voice media is not ready in this browser.`);try{r=await a.prepareSessionActivation(e,i)}catch(r){throw R.update(r=>{if(r?.sessionId!==e||!r.ownershipConflict)return r;let i=r.ownershipConflict.owner.generation;return{...r,actions:{takeOver:()=>{D(()=>O(t,n,void 0,i))},retry:()=>{D(()=>O(t,n))}}}}),r}}if(t===`switch`&&n===`live`&&!r){let e=tt.store.state;if(!e)throw Error(`Voice media is not ready in this browser.`);r=await e.prepareLiveActivation(i)}let a=await V.session(e).control({body:{action:t,...n?{mode:n}:{},...r?{browser:r}:{},...i===void 0?{}:{takeoverGeneration:i}}});if(a.ok&&a.data.ownershipConflict){let r=a.data.ownershipConflict,o=i!==void 0;R.update(()=>({sessionId:e,phase:`conflict`,ownershipConflict:r,ownership:{kind:o?`stale`:`conflict`,ownerName:r.owner.deviceName},actions:{takeOver:()=>{D(()=>O(t,n,void 0,r.owner.generation))},retry:()=>{D(()=>O(t,n))}}}))}else if(!a.ok)throw Error(a.error||`Voice control request failed.`)},k=async(t,n)=>{if(e===null)return;g(!1);let r={sessionId:e,mode:t};nt.update(()=>r);try{await n()}finally{nt.update(e=>e===r?void 0:e)}},te=(e,t)=>D(()=>k(e,t)),ne=()=>D(async()=>{let e=await V.host.liveStatus();if(e.ok&&e.data.signedIn===!1){g(!0);return}if(!e.ok)throw Error(e.error);if(e.data.state!==`disabled`)return;let t=tt.store.state;if(!t)throw Error(`Voice media is not ready in this browser.`);let n=await t.prepareLiveActivation();await k(`live`,()=>O(`switch`,`live`,n))}),re=()=>te(`legacy`,async()=>{b&&await ie(`end`),await O(`activate`,`legacy`)}),ie=async e=>{let t=await V.host.liveControl({body:{action:e}});if(!t.ok)throw Error(t.error||`Live control request failed.`)},ae=()=>T?T.end():void D(()=>ie(`end`)),A={},oe,j=(t,n,r=!1)=>{e!==null&&b&&(oe={value:n,disabled:r,onPick:t})};switch(E.kind){case`switching`:j(()=>void 0,E.mode,!0);break;case`daily`:if(e===null)break;j(e=>void(e===`live`?ne():void 0),`legacy`),i.phase!==`starting`&&i.phase!==`draining`&&(A.mute=()=>void D(()=>O(i.microphoneMuted?`unmute`:`mute`))),A.end=()=>void D(()=>O(`deactivate`)),n&&(A.signIn=()=>n(`providers`));break;case`live`:{let e=E.realtime?.muted===!0;j(e=>void(e===`legacy`?re():void 0),`live`),A.mute=()=>T?T.mute(!e):void D(()=>ie(e?`unmute`:`mute`)),A.interrupt=()=>T?T.interrupt():void D(()=>ie(`interrupt`)),A.end=ae;break}case`live-failed`:j(e=>void(e===`legacy`?re():void 0),`live`),e!==null&&(A.useDailyWork=()=>void re()),A.end=ae;break;case`live-elsewhere`:j(()=>void 0,`live`,!0),e!==null&&(A.routeLiveHere=()=>void D(async()=>{let t=await V.host.liveControl({body:{action:`transfer`,sessionId:e}});if(!t.ok)throw Error(t.error||`Moving Live here failed.`)}));break;case`daily-elsewhere`:j(()=>void 0,`legacy`,!0),e!==null&&(A.moveDailyWorkHere=()=>void D(()=>O(`activate`,`legacy`)))}let se=a?.sessionId===e||a?.sessionId===null?a:void 0;return l(Ot,{state:E,picker:oe,actions:A,pending:d,error:p,ownership:se?.ownership,ownershipActions:se?.actions})}function jt(e){let t=w(R.store);return e.sessionId!==null||t?.sessionId!==null||t.realtime?.connection===`closed`||t.realtime===void 0?null:l(At,{...e})}var Mt=ue({slot:`activity`,id:`voice-global-live`,component:jt}),Nt=1e4,Pt=15e3,Ft=15e3;function It(e){return new TextEncoder().encode(e).byteLength}function Lt(e){if(typeof e!=`object`||!e)return;let t=e.type;return typeof t==`string`?t:void 0}function W(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}var Rt=class{options;microphoneConstraints;browser;output;state={connection:`closed`,listening:!1,speaking:!1,muted:!1};generation=0;started=!1;stream;peer;channel;audio;abortController;suppressOutput=!1;announcements=new Map;announcementFlushScheduled=!1;constructor(e,t=async()=>F,n=window,r){this.options=e,this.microphoneConstraints=t,this.browser=n,this.output=r,this.state.muted=e.muted===!0,r&&(r.onPlaybackState=e=>{this.state.connection!==`closed`&&this.state.connection!==`failed`&&(this.publish({speaking:e&&!this.suppressOutput}),e||this.scheduleAnnouncementFlush())})}async start(){if(this.started)throw Error(`Realtime browser session has already started.`);this.started=!0;let e=++this.generation,t=new AbortController;this.abortController=t,this.publish({connection:`connecting`,error:void 0});try{if(typeof this.browser.RTCPeerConnection!=`function`||this.browser.navigator.mediaDevices?.getUserMedia===void 0)throw Error(`Browser realtime media is unavailable.`);let n=this.microphoneConstraints().then(e=>this.browser.navigator.mediaDevices.getUserMedia(e));n.then(t=>{if(!this.isCurrent(e))for(let e of t.getTracks())e.stop()},()=>void 0);let r=await this.abortable(n,t.signal);if(!this.isCurrent(e)){for(let e of r.getTracks())e.stop();throw Error(`Realtime browser session was closed.`)}this.stream=r;for(let t of r.getTracks())t.kind===`audio`&&(t.enabled=!this.state.muted),t.onended=()=>this.fail(e,`Microphone permission or input was lost.`);let i=new this.browser.RTCPeerConnection;this.peer=i,i.onconnectionstatechange=()=>{this.isCurrent(e)&&(i.connectionState===`failed`||i.connectionState===`disconnected`?this.fail(e,`Realtime connection ${i.connectionState}.`):i.connectionState===`closed`&&this.state.connection!==`closed`&&this.fail(e,`Realtime connection closed unexpectedly.`))},i.ontrack=t=>this.attachRemoteAudio(e,t);let a=i.createDataChannel(`oai-events`);this.channel=a,a.onmessage=t=>this.receive(e,t.data),a.onerror=()=>this.fail(e,`Realtime event channel failed.`),a.onclose=()=>{this.isCurrent(e)&&this.fail(e,`Realtime event channel closed unexpectedly.`)};for(let e of r.getTracks())i.addTrack(e,r);let o=await i.createOffer();this.assertSdp(o.sdp),await i.setLocalDescription(o),await this.waitForIce(i,e,t.signal);let s=i.localDescription?.sdp;this.assertSdp(s);let c=await this.bounded(this.options.negotiate(s,t.signal),Ft,`Realtime negotiation timed out.`,t.signal);if(this.assertSdp(c),!this.isCurrent(e)||(await i.setRemoteDescription({type:`answer`,sdp:c}),await this.waitForConnection(i,a,e,t.signal),!this.isCurrent(e)))throw Error(`Realtime browser session was closed.`);this.publish({connection:`connected`,listening:!this.state.muted})}catch(t){throw this.isCurrent(e)&&this.fail(e,W(t)),t}}send(e){if(this.validateEvent(e),this.channel?.readyState!==`open`||this.state.connection!==`connected`)throw Error(`Realtime event channel is not open.`);let t=JSON.parse(e);if(t.type===`po.announce`){if(typeof t.key!=`string`||t.key.length===0||t.text!==void 0&&typeof t.text!=`string`)throw Error(`Realtime announcement requires a key and optional text.`);t.text===void 0?this.announcements.delete(t.key):this.announcements.set(t.key,t.text),this.scheduleAnnouncementFlush()}else this.channel.send(e)}mute(e){for(let t of this.stream?.getAudioTracks()??[])t.enabled=!e;this.publish({muted:e,listening:this.state.connection===`connected`&&!e})}interruptSpeech(){this.suppressOutput=!0,this.audio!==void 0&&(this.audio.muted=!0),this.output?.suppress(!0),this.publish({speaking:!1})}close(){this.state.connection===`closed`&&this.generation>0||(this.started=!0,this.generation+=1,this.cleanup(),this.publish({connection:`closed`,listening:!1,speaking:!1,error:void 0}))}receive(e,t){if(!this.isCurrent(e))return;if(typeof t!=`string`||It(t)>dt.eventBytes){this.fail(e,`Realtime provider sent an invalid or oversized event.`);return}let n;try{n=JSON.parse(t)}catch{this.fail(e,`Realtime provider sent malformed JSON.`);return}let r=Lt(n);if(r===void 0)this.fail(e,`Realtime provider sent an event without a type.`);else if(r===`error`)this.fail(e,`Realtime provider reported an error.`);else if(r===`input_transcript.added`&&this.suppressOutput&&(this.suppressOutput=!1,this.audio!==void 0&&(this.audio.muted=!1),this.output?.suppress(!1)),ft.has(r))try{this.options.onEvent(t)}catch(t){this.fail(e,`Realtime event consumer failed: ${W(t)}`)}}attachRemoteAudio(e,t){if(!this.isCurrent(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??new this.browser.MediaStream([t.track]);if(this.output){this.output.suppress(this.suppressOutput);try{Promise.resolve(this.output.attach(n,t.track)).catch(t=>this.fail(e,`Remote audio playback failed: ${W(t)}`))}catch(t){this.fail(e,`Remote audio playback failed: ${W(t)}`)}return}let r=this.browser.document.createElement(`audio`);r.autoplay=!0,r.muted=this.suppressOutput,r.srcObject=n,r.onplaying=()=>{this.isCurrent(e)&&this.audio===r&&!r.muted&&this.publish({speaking:!0})};let i=()=>{this.isCurrent(e)&&this.audio===r&&(this.publish({speaking:!1}),this.scheduleAnnouncementFlush())};r.onpause=i,r.onended=i,r.onwaiting=i,this.detachAudio(),this.audio=r,r.play().catch(t=>this.fail(e,`Remote audio playback failed: ${W(t)}`))}scheduleAnnouncementFlush(){if(this.announcementFlushScheduled||this.announcements.size===0)return;this.announcementFlushScheduled=!0;let e=this.generation;queueMicrotask(()=>{if(this.announcementFlushScheduled=!1,!this.isCurrent(e)||this.state.connection!==`connected`||this.channel?.readyState!==`open`||this.suppressOutput)return;let t=e=>JSON.stringify({type:`session.context.append`,channel:`speakable`,content:[{type:`input_text`,text:`Share these updates only at a conversational pause. Stop and listen when the user speaks.\n\n${e}`}]}),n=[],r=``;for(let e of this.announcements.values()){let i=Array.from(e);for(let e=0;e<i.length;e+=4096){let a=i.slice(e,e+4096).join(``),o=r?`${r}\n\n${a}`:a;It(t(o))>dt.eventBytes?(n.push(t(r)),r=a):r=o}}r&&n.push(t(r)),this.announcements.clear();try{for(let e of n)this.channel.send(e)}catch(t){this.fail(e,`Realtime announcement failed: ${W(t)}`)}})}validateEvent(e){if(It(e)>dt.eventBytes)throw Error(`Realtime event exceeds the maximum size.`);let t;try{t=JSON.parse(e)}catch{throw Error(`Realtime event must be valid JSON.`)}if(Lt(t)===void 0)throw Error(`Realtime event must contain a type.`)}assertSdp(e){if(typeof e!=`string`||e.length===0)throw Error(`Realtime SDP is missing.`);if(It(e)>dt.sdpBytes)throw Error(`Realtime SDP exceeds the maximum size.`)}async waitForIce(e,t,n){if(e.iceGatheringState===`complete`)return;let r=()=>{this.isCurrent(t)&&e.iceGatheringState===`complete`&&i?.()},i;try{await this.bounded(new Promise(t=>{i=t,e.addEventListener(`icegatheringstatechange`,r),r()}),Nt,`Realtime ICE gathering timed out.`,n)}finally{e.removeEventListener(`icegatheringstatechange`,r)}}async waitForConnection(e,t,n,r){let i=()=>e.connectionState===`connected`&&t.readyState===`open`;if(i())return;let a=()=>{this.isCurrent(n)&&(e.connectionState===`failed`||e.connectionState===`disconnected`?s?.(Error(`Realtime connection ${e.connectionState}.`)):i()&&o?.())},o,s;try{await this.bounded(new Promise((n,r)=>{o=n,s=r,e.addEventListener(`connectionstatechange`,a),t.addEventListener(`open`,a),t.addEventListener(`close`,a),a()}),Pt,`Realtime connection timed out.`,r)}finally{e.removeEventListener(`connectionstatechange`,a),t.removeEventListener(`open`,a),t.removeEventListener(`close`,a)}}abortable(e,t){return new Promise((n,r)=>{let i=!1,a=e=>{i||(i=!0,t.removeEventListener(`abort`,o),e())},o=()=>a(()=>r(Error(`Realtime browser session was closed.`)));t.addEventListener(`abort`,o,{once:!0}),t.aborted&&o(),e.then(e=>a(()=>n(e)),e=>a(()=>r(e)))})}bounded(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(l),r.removeEventListener(`abort`,c),e())},c=()=>s(()=>a(Error(`Realtime browser session was closed.`))),l=setTimeout(()=>s(()=>a(Error(n))),t);r.addEventListener(`abort`,c,{once:!0}),r.aborted&&c(),e.then(e=>s(()=>i(e)),e=>s(()=>a(e)))})}fail(e,t){this.isCurrent(e)&&(this.generation+=1,this.cleanup(),this.publish({connection:`failed`,listening:!1,speaking:!1,error:t}))}cleanup(){this.announcements.clear(),this.abortController?.abort(),this.abortController=void 0,this.channel!==void 0&&(this.channel.onmessage=null,this.channel.onerror=null,this.channel.onclose=null,this.channel.close()),this.peer!==void 0&&(this.peer.ontrack=null,this.peer.onconnectionstatechange=null,this.peer.close());for(let e of this.stream?.getTracks()??[])e.onended=null,e.stop();this.detachAudio(),this.output&&(this.output.onPlaybackState=null,this.output.dispose()),this.channel=void 0,this.peer=void 0,this.stream=void 0,this.suppressOutput=!1}detachAudio(){this.audio!==void 0&&(this.audio.onplaying=null,this.audio.onpause=null,this.audio.onended=null,this.audio.onwaiting=null,this.audio.pause(),this.audio.srcObject=null,this.audio=void 0)}publish(e){this.state={...this.state,...e};try{this.options.onState({...this.state})}catch(e){queueMicrotask(()=>{throw e})}}isCurrent(e){return this.generation===e}},zt=600,Bt=N*120/1e3,Vt=-120,Ht=32768,Ut=2,Wt=N*1*Ut;function Gt(e,t,n){return Math.min(n,Math.max(t,e))}function Kt(e){return Math.round(e*10)/10}function qt(e){if(e.byteLength===0||e.byteLength%Ut!==0)throw Error(`PCM activity input must contain complete 16-bit samples.`);let t=0;for(let n=0;n<e.byteLength;n+=Ut){let r=e[n]|e[n+1]<<8,i=(r>=32768?r-65536:r)/Ht;t+=i*i}let n=Math.sqrt(t/(e.byteLength/Ut));return n===0?Vt:20*Math.log10(n)}var Jt=class{endpointSilenceMs;elapsedBytes=0;activityEpoch=0;consecutiveSpeechSamples=0;consecutiveEchoSpeechSamples=0;classifiedSpeechSamples=0;echoDiscriminatedSpeechSamples=0;trailingSilenceSamples=0;speechStarted=!1;endpointReached=!1;previousEchoDiscriminated=!1;constructor(e=zt){if(this.endpointSilenceMs=e,!Number.isSafeInteger(e)||e<250)throw Error(`Client endpoint silence must be an integer of at least 250 ms.`)}push(e,t=[],n){let r=qt(e);this.elapsedBytes+=e.byteLength;let i=n?.echoReferenceActive===!0&&n.echoDiscriminated&&this.previousEchoDiscriminated;for(let e of t){if(!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0)throw Error(`Speech-presence windows must contain a positive integer sample count.`);if(this.endpointReached){if(!e.speech){this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0;continue}if(this.consecutiveSpeechSamples+=e.sampleCount,i&&(this.consecutiveEchoSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples<Bt)continue;this.activityEpoch+=1,this.classifiedSpeechSamples=this.consecutiveSpeechSamples,this.echoDiscriminatedSpeechSamples=this.consecutiveEchoSpeechSamples,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.trailingSilenceSamples=0,this.speechStarted=!0,this.endpointReached=!1;continue}e.speech?(this.classifiedSpeechSamples+=e.sampleCount,i&&(this.echoDiscriminatedSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples+=e.sampleCount,i&&(this.consecutiveEchoSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples>=Bt&&(this.speechStarted=!0,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.trailingSilenceSamples=0)):(this.speechStarted&&(this.trailingSilenceSamples+=this.consecutiveSpeechSamples+e.sampleCount),this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0);let t=this.trailingSilenceSamples/N*1e3;this.speechStarted&&t>=this.endpointSilenceMs&&(this.endpointReached=!0)}return this.previousEchoDiscriminated=n?.echoReferenceActive===!0&&n.echoDiscriminated,{state:this.endpointReached?`endpoint`:this.speechStarted?`speech`:`listening`,levelDbfs:Kt(Gt(r,Vt,0)),elapsedMs:Math.round(this.elapsedBytes/Wt*1e3),epoch:this.activityEpoch,classifiedSpeechMs:Math.round(this.classifiedSpeechSamples/N*1e3),...n?.echoReferenceActive===!0?{echoDiscriminatedSpeechMs:Math.round(this.echoDiscriminatedSpeechSamples/N*1e3)}:{}}}resetActivity(){this.activityEpoch+=1,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.classifiedSpeechSamples=0,this.echoDiscriminatedSpeechSamples=0,this.trailingSilenceSamples=0,this.speechStarted=!1,this.endpointReached=!1,this.previousEchoDiscriminated=!1}},Yt=2e3,Xt=16e3,Zt=200,Qt=128,$t=2097152,en=409;function tn(e){return e instanceof Error&&`status`in e&&e.status===en}function nn(e){if(!(e instanceof Error)||!(`conflict`in e))return!1;let t=e.conflict;return typeof t==`object`&&!!t&&`code`in t&&t.code===`VOICE_OWNERSHIP_CONFLICT`}function rn(e,t){return{playbackId:e,outcome:`failed`,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}function an(e){return{...e}}function on(e,t){return e.capture===t.capture&&e.playback===t.playback&&e.captureActivity===t.captureActivity&&e.autonomousOrchestration===t.autonomousOrchestration&&e.playbackDucking===t.playbackDucking&&e.realtime===t.realtime}function sn(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0})})}var cn=class{clientId;connectionId;transport;device;onConnectionState;onRealtimeState;createRealtimeSession;onOpenSession;abortController=new AbortController;capture;captureId;advertisedCapabilities;captureGeneration=0;speechDetector;activityLifecycle;playback;playbackAudioController;audioUploads=Promise.resolve();audioUploadError;activeConnectionId;connectionAttempt=0;ownershipError;connectionWaiters=new Set;failAttempt;runOperation;realtime;realtimeActivationId;realtimeGeneration=0;realtimePosts=Promise.resolve();pendingRealtimePosts=0;listeningWaiters=new Set;captureEndWaiters=new Set;constructor(e,t,n,r,i=()=>void 0,a=()=>void 0,o,s){this.clientId=e,this.connectionId=t,this.transport=n,this.device=r,this.onConnectionState=i,this.onRealtimeState=a,this.createRealtimeSession=o,this.onOpenSession=s}start(){this.onConnectionState(`connecting`),this.runOperation??=this.run()}waitForConnection(){return this.activeConnectionId===void 0?this.ownershipError?Promise.reject(this.ownershipError):this.abortController.signal.aborted?Promise.reject(Error(`Voice media client is closed.`)):new Promise((e,t)=>{let n=i=>{clearTimeout(r),this.connectionWaiters.delete(n),i?t(i):this.activeConnectionId===void 0?t(Error(`Voice media connection is unavailable.`)):e({clientId:this.clientId,connectionId:this.activeConnectionId})},r=setTimeout(()=>n(Error(`The requesting browser did not connect to Voice.`)),1e4);this.connectionWaiters.add(n)}):Promise.resolve({clientId:this.clientId,connectionId:this.activeConnectionId})}get listening(){return this.capture!==void 0}waitForListening(){return this.listening?Promise.resolve(!0):this.abortController.signal.aborted?Promise.resolve(!1):new Promise(e=>this.listeningWaiters.add(e))}waitForCaptureEnd(){return this.captureId===void 0||this.abortController.signal.aborted?Promise.resolve():new Promise(e=>this.captureEndWaiters.add(e))}async stop(e=!0){this.closeRealtime(),this.abortController.abort();for(let e of this.connectionWaiters)e(Error(`Voice media client is closed.`));await this.runOperation?.catch(()=>void 0),await this.releaseMedia(e);let t=this.activeConnectionId;t!==void 0&&await this.transport.disconnect(this.clientId,t).catch(()=>void 0),this.activeConnectionId=void 0,this.advertisedCapabilities=void 0,this.resolveListening(!1),this.resolveCaptureEnd(),this.onConnectionState(`disconnected`)}async run(){let e=this.abortController.signal,t=Yt;for(;!e.aborted;){let n=this.nextConnectionId(),r=new AbortController,i=()=>r.abort();e.addEventListener(`abort`,i,{once:!0});let a,o=new Promise((e,t)=>{a=t});this.failAttempt=a;try{let i=an(this.device.capabilities),a=await this.transport.connect(this.clientId,n,i);if(e.aborted){await this.transport.disconnect(this.clientId,n).catch(()=>void 0);return}this.activeConnectionId=n,this.advertisedCapabilities=i,t=Yt,this.onConnectionState(`connected`);for(let e of this.connectionWaiters)e();this.prepareCapabilities(n,i,r.signal);let s=a.cursor;for(;!e.aborted;){let e=await Promise.race([this.transport.nextEvent(this.clientId,n,s,r.signal),o]);e!==void 0&&(s=e.sequence,await this.handle(e,n))}}catch(i){for(let e of this.connectionWaiters)e(i instanceof Error?i:Error(String(i)));if(e.aborted)return;if(tn(i)&&(this.activeConnectionId!==n||nn(i))&&this.onConnectionState(`conflict`,i),r.abort(),this.closeRealtime(tn(i)),await this.releaseMedia(),this.activeConnectionId===n&&(await this.transport.disconnect(this.clientId,n).catch(()=>void 0),this.activeConnectionId=void 0,this.advertisedCapabilities=void 0),tn(i)&&nn(i)){this.ownershipError=i;return}await sn(t,e),t=Math.min(t*2,Xt)}finally{e.removeEventListener(`abort`,i),this.failAttempt===a&&(this.failAttempt=void 0)}}}prepareCapabilities(e,t,n){(async()=>{try{if(await this.device.prepare?.(),n.aborted||this.abortController.signal.aborted||this.activeConnectionId!==e)return;let r=an(this.device.capabilities);if(on(t,r)||!this.transport.refreshCapabilities)return;await this.transport.refreshCapabilities(this.clientId,e,r),this.activeConnectionId===e&&(this.advertisedCapabilities=r)}catch{}})()}async handle(e,t){switch(e.type){case`realtime-start`:this.startRealtime(e.activationId,t,e.muted===!0);return;case`realtime-stop`:this.realtimeActivationId===e.activationId&&this.closeRealtime();return;case`realtime-control`:if(this.realtimeActivationId!==e.activationId)return;e.action===`mute`?this.realtime?.mute(!0):e.action===`unmute`?this.realtime?.mute(!1):this.realtime?.interruptSpeech();return;case`realtime-send`:if(this.realtimeActivationId!==e.activationId)return;for(let t of e.messages)this.realtime?.send(t);return;case`open-session`:this.realtimeActivationId===e.activationId&&this.onOpenSession?.(e.sessionId);return;case`capture-start`:this.closeRealtime(),await this.startCapture(e,t);return;case`capture-stop`:this.captureId===e.captureId&&await this.finishCapture(e.captureId,t,!0);return;case`capture-abort`:this.captureId===e.captureId&&await this.finishCapture(e.captureId,t,!1);return;case`playback-start`:this.closeRealtime(),await this.startPlayback(e,t);return;case`playback-stop`:this.playbackAudioController?.abort(),this.playback?.stop(`stopped`);return;case`playback-abort`:this.playbackAudioController?.abort(),this.playback?.stop(`aborted`);return}}muteRealtime(e){this.realtime?.mute(e)}interruptRealtime(){this.realtime?.interruptSpeech()}endRealtime(){this.closeRealtime()}startRealtime(e,t,n){this.closeRealtime();let r=++this.realtimeGeneration;this.realtimeActivationId=e,this.beginRealtime(e,t,r,n).catch(e=>this.failRealtime(r,e))}async beginRealtime(e,t,n,r){if(await this.releaseMedia(!1),!this.isCurrentRealtime(e,t,n))return;let{realtimeNegotiate:i,realtimeEvent:a,realtimeState:o}=this.transport;if(i===void 0||a===void 0||o===void 0)throw Error(`Realtime browser transport is unavailable.`);let s;if(!this.createRealtimeSession)throw Error(`Realtime media device is unavailable.`);s=this.createRealtimeSession({muted:r,negotiate:(n,r)=>i.call(this.transport,this.clientId,t,e,n,r),onEvent:r=>{this.realtime===s&&this.isCurrentRealtime(e,t,n)&&this.enqueueRealtimePost(n,()=>a.call(this.transport,this.clientId,t,e,r))},onState:r=>{this.realtime===s&&this.isCurrentRealtime(e,t,n)&&(this.onRealtimeState(r),this.enqueueRealtimePost(n,()=>o.call(this.transport,this.clientId,t,e,r)))}}),this.realtime=s,await s.start()}closeRealtime(e=!1){let t=this.realtime,n=this.realtimeActivationId;if(t===void 0&&n===void 0)return;let r=this.activeConnectionId,i=this.realtimeGeneration;this.realtime=void 0,this.realtimeActivationId=void 0,this.realtimeGeneration+=1,t?.close(),this.onRealtimeState(void 0,e);let a=this.transport.realtimeState;n!==void 0&&r!==void 0&&a!==void 0&&this.enqueueRealtimePost(i,()=>a.call(this.transport,this.clientId,r,n,{connection:`closed`,listening:!1,speaking:!1,muted:!1}),!0)}isCurrentRealtime(e,t,n){return this.realtimeGeneration===n&&this.realtimeActivationId===e&&this.activeConnectionId===t&&!this.abortController.signal.aborted}enqueueRealtimePost(e,t,n=!1){if(this.pendingRealtimePosts>=Qt){this.failRealtime(e,Error(`Realtime browser event queue exceeded its limit.`));return}this.pendingRealtimePosts+=1;let r=this.realtimePosts.then(()=>{if(n||e===this.realtimeGeneration)return t()});this.realtimePosts=r.catch(()=>void 0),r.then(()=>{--this.pendingRealtimePosts},t=>{--this.pendingRealtimePosts,this.failRealtime(e,t)})}failRealtime(e,t){e===this.realtimeGeneration&&(this.closeRealtime(),this.onRealtimeState({connection:`failed`,listening:!1,speaking:!1,muted:!1,error:t instanceof Error?t.message:String(t)}),this.failAttempt?.(t instanceof Error?t:Error(String(t))))}async startCapture(e,t){let{captureId:n,configuration:r}=e;this.capture!==void 0&&await this.finishCapture(this.captureId??n,t,!1);let i=++this.captureGeneration;this.captureId=n,this.audioUploads=Promise.resolve(),this.audioUploadError=void 0;let a=0,o=r.activityControl===`client`?this.device.createSpeechPresenceDetector?.():void 0,s=r.activityControl===`client`&&o!==void 0?new Jt(r.endpointSilenceMs):void 0;this.speechDetector=o,this.activityLifecycle=s;try{let e=await this.device.startCapture((e,r)=>{if(i!==this.captureGeneration||this.captureId!==n||this.audioUploadError!==void 0)return;if(a+e.byteLength>$t){let e=Error(`Voice PCM upload queue exceeded its limit. The local recording is retained.`);this.audioUploadError=e,this.failActiveCapture(n,t,i,e);return}a+=e.byteLength;let c=new Uint8Array(e),l=r===void 0?c:new Uint8Array(r.speechPcm),u=r===void 0?void 0:{echoReferenceActive:r.echoReferenceActive,echoDiscriminated:r.echoDiscriminated};this.audioUploads=this.audioUploads.then(async()=>{if(a-=c.byteLength,this.audioUploadError===void 0&&i===this.captureGeneration&&this.captureId===n)try{if(l.byteLength!==c.byteLength)throw Error(`Local speech analysis must preserve the capture sample count.`);let e=await o?.push(l);if(i!==this.captureGeneration||this.captureId!==n)return;let r=s?.push(c,e,u);await this.transport.sendAudio(this.clientId,t,n,c,r)}catch(e){if(i!==this.captureGeneration||this.captureId!==n)return;let r=e instanceof Error?e:Error(String(e));tn(r)||(this.audioUploadError=r),await this.failActiveCapture(n,t,i,r)}})});if(i!==this.captureGeneration||this.captureId!==n||this.abortController.signal.aborted){await e.stop();return}this.capture=e,e.completion?.catch(e=>this.failActiveCapture(n,t,i,e instanceof Error?e:Error(String(e)))),this.resolveListening(!0)}catch(e){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e);throw await this.transport.captureStopped(this.clientId,t,n,r).catch(()=>void 0),this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),e}}async failActiveCapture(e,t,n,r){if(n!==this.captureGeneration||this.captureId!==e)return;let i=this.capture;this.capture=void 0,await i?.stop().catch(()=>void 0),n===this.captureGeneration&&this.captureId===e&&(this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),tn(r)?await this.speechDetector?.reset().catch(()=>void 0):(this.transport.captureStopped(this.clientId,t,e,`${r.name}: ${r.message}`).catch(()=>void 0),this.failAttempt?.(r)))}async finishCapture(e,t,n){let r=this.advertisedCapabilities;await this.capture?.stop(),this.capture=void 0,await this.audioUploads,await this.speechDetector?.reset().catch(()=>void 0),this.speechDetector=void 0,this.activityLifecycle=void 0;let i=an(this.device.capabilities);if(r!==void 0&&!on(r,i)&&this.transport.refreshCapabilities)try{await this.transport.refreshCapabilities(this.clientId,t,i),this.activeConnectionId===t&&(this.advertisedCapabilities=i)}catch{}if(this.audioUploadError!==void 0){let n=this.audioUploadError;throw await this.transport.captureStopped(this.clientId,t,e,`${n.name}: ${n.message}`).catch(()=>void 0),this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),n}this.captureId=void 0,this.captureGeneration+=1,this.resolveListening(!1);try{n&&await this.transport.captureStopped(this.clientId,t,e)}finally{this.resolveCaptureEnd()}}async startPlayback(e,t){this.playbackAudioController?.abort(),this.playback?.stop(`aborted`),this.scheduleActivityReset();let n=e.delivery===`streamed`?new AbortController:void 0;this.playbackAudioController=n;let r=n?this.transport.receivePlaybackAudio?.(this.clientId,t,e.playbackId,n.signal):void 0,i;try{i=this.device.speak(e,r)}catch(r){n?.abort(),await this.transport.playbackFinished(this.clientId,t,rn(e.playbackId,r)),this.scheduleActivityReset();return}this.playback=i,i.completion.then(e=>this.transport.playbackFinished(this.clientId,t,e),n=>this.transport.playbackFinished(this.clientId,t,rn(e.playbackId,n))).catch(e=>{this.activeConnectionId!==t||this.abortController.signal.aborted||this.failAttempt?.(e instanceof Error?e:Error(String(e)))}).finally(()=>{this.playback===i&&(n?.abort(),this.playbackAudioController===n&&(this.playbackAudioController=void 0),this.playback=void 0,this.scheduleActivityReset())})}scheduleActivityReset(){let e=this.captureGeneration,t=this.activityLifecycle,n=this.speechDetector;t&&n&&(this.audioUploads=this.audioUploads.then(async()=>{e===this.captureGeneration&&t===this.activityLifecycle&&n===this.speechDetector&&(t.resetActivity(),await n.reset().catch(()=>void 0))}))}async releaseMedia(e=!0){this.captureGeneration+=1;let t=this.capture,n=this.audioUploads,r=this.speechDetector;this.capture=void 0,this.audioUploads=Promise.resolve(),this.speechDetector=void 0,this.activityLifecycle=void 0,this.captureId=void 0,this.resolveCaptureEnd(),this.audioUploadError=void 0,await t?.stop().catch(()=>void 0),this.resolveListening(!1),n.catch(()=>void 0),r?.reset().catch(()=>void 0),this.playbackAudioController?.abort(),this.playbackAudioController=void 0,this.playback?.stop(`aborted`),this.playback=void 0,e&&await this.device.close().catch(()=>void 0)}resolveListening(e){for(let t of this.listeningWaiters)t(e);this.listeningWaiters.clear()}resolveCaptureEnd(){for(let e of this.captureEndWaiters)e();this.captureEndWaiters.clear()}nextConnectionId(){let e=`:${(++this.connectionAttempt).toString(36)}`;return`${this.connectionId.slice(0,Zt-e.length)}${e}`}},ln=globalThis,un=Symbol.for(`@agimon-ai/po-voice:microphone-preferences.v2`),dn=globalThis,G=dn[un]??=m({inputs:[]}),fn=`po.voice.microphone.v1`;function pn(){try{let e=ln.localStorage.getItem(fn);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let{deviceId:n,inputs:r}=t;return n!==null&&typeof n!=`string`||!Array.isArray(r)||r.some(e=>typeof e!=`string`)?void 0:{deviceId:n,inputs:r}}catch{return}}function mn(e){try{ln.localStorage.setItem(fn,JSON.stringify(e))}catch{}}async function hn(){let e=(await ln.navigator.mediaDevices.enumerateDevices().catch(()=>[])).filter(e=>e.kind===`audioinput`&&e.deviceId&&e.deviceId!=="default"&&e.deviceId!==`communications`).map(({deviceId:e,groupId:t,label:n})=>({deviceId:e,groupId:t,label:n}));return G.update(t=>({...t,inputs:e})),e}function gn(){return G.store.state.choice===void 0?new Promise(e=>{G.update(t=>({...t,choice:(t,n)=>{G.update(e=>({...e,choice:void 0})),e({deviceId:t,remember:n})}}))}):Promise.resolve({deviceId:null,remember:!1})}function _n(){G.store.state.choice?.(null,!1)}async function vn(){let e;try{(await ln.navigator.mediaDevices.enumerateDevices().catch(()=>[])).some(e=>e.kind===`audioinput`&&e.label)||(e=await ln.navigator.mediaDevices.getUserMedia(F));let t=await hn();if(t.length<2)return F;let n=t.map(e=>e.deviceId).sort(),r=pn();if(r!==void 0&&r.inputs.join()===n.join())return r.deviceId===null?F:Re(r.deviceId);let{deviceId:i,remember:a}=await gn();return a&&mn({deviceId:i,inputs:n}),i===null?F:Re(i)}finally{e?.getTracks().forEach(e=>e.stop())}}var yn=new URL(new URL(`../assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js`,import.meta.url).href,``+import.meta.url).href,bn=2,xn=32768,Sn=2e3,Cn=300,wn=500,Tn=800,En=20,Dn=4,On=16,kn=-55,An=-50,jn=.65,Mn=.75,Nn=.25,Pn=.35,Fn=.35,In=.5,Ln=4,Rn=.98,zn=.01,Bn=N*Sn/1e3,Vn=N*Cn/1e3,Hn=N*wn/1e3,Un=Tn/1e3,Wn=N*En/1e3;function Gn(e,t,n){return Math.min(n,Math.max(t,e))}function Kn(e){if(e.byteLength===0||e.byteLength%bn!==0)throw Error(`Echo-discrimination input must contain complete PCM16 samples.`);let t=new Float32Array(e.byteLength/bn),n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t.length;e+=1)t[e]=n.getInt16(e*2,!0)/xn;return t}function qn(e){let t=new Uint8Array(e.length*bn),n=new DataView(t.buffer);for(let t=0;t<e.length;t+=1){let r=Gn(e[t]??0,-1,1);n.setInt16(t*bn,Math.round(r<0?r*xn:r*32767),!0)}return t}function Jn(e,t){let n=Math.min(e.length,Math.max(0,Bn-t.length)),r=new Float32Array(n+t.length);return n>0&&r.set(e.subarray(e.length-n)),r.set(t,n),r}function Yn(e){return e<=0?-1/0:10*Math.log10(e)}function Xn(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n*n;return t/e.length}function Zn(e){if(e.length===0)return 0;let t=0;for(let n of e)Math.abs(n)>=Rn&&(t+=1);return t/e.length}function Qn(e,t,n,r,i,a){let o=0,s=0,c=0;for(let l=0;l<i;l+=a){let i=e[n+l],a=t[r+l];i!==void 0&&a!==void 0&&(o+=i,s+=a,c+=1)}if(c<2)return 0;let l=o/c,u=s/c,d=0,f=0,p=0;for(let o=0;o<i;o+=a){let i=e[n+o],a=t[r+o];if(i===void 0||a===void 0)continue;let s=i-l,c=a-u;d+=s*c,f+=s*s,p+=c*c}let m=Math.sqrt(f*p);return m<=2**-52?0:d/m}function $n(e,t,n,r,i){let a=[],o=[];for(let s=0;s+Wn<=i;s+=Wn){let i=0,c=0;for(let a=0;a<Wn;a+=1){let o=e[n+s+a]??0,l=t[r+s+a]??0;i+=o*o,c+=l*l}a.push(Math.log10(Math.max(2**-52,i/Wn))),o.push(Math.log10(Math.max(2**-52,c/Wn)))}return a.length<3?0:Qn(Float32Array.from(a),Float32Array.from(o),0,0,a.length,1)}function er(e){return new Uint8Array(e.byteLength)}var tr=class{references=[];microphoneHistory=new Float32Array;referenceHistory=new Float32Array;beginPlayback(e,t,n){if(e&&t.length!==0&&Number.isFinite(n)){for(let e of this.references)e.endedAt===void 0&&this.finishReference(e,n);this.references.push({playbackId:e,samples:t,startedAt:n})}}endPlayback(e,t){if(!Number.isFinite(t))return;let n=this.references.slice().reverse().find(t=>t.playbackId===e);n!==void 0&&n.endedAt===void 0&&this.finishReference(n,t)}process(e,t){let n=Kn(e);if(!Number.isFinite(t))return this.unavailable(e,n);let r=t-n.length/N;this.pruneReferences(r);let i=this.renderReference(r,n.length);if(this.microphoneHistory=Jn(this.microphoneHistory,n),this.referenceHistory=Jn(this.referenceHistory,i.samples),!i.tracked)return{speechPcm:new Uint8Array(e),referenceActive:!1,speechDiscriminated:!1,state:`unavailable`};let a=Math.min(Vn,this.microphoneHistory.length),o=this.microphoneHistory.length-a,s=this.referenceHistory.length-a,c=Math.min(Hn,s),l=Math.max(0,s-c),u=this.referenceHistory.subarray(l),d=this.microphoneHistory.subarray(o),f=Yn(Xn(d));if(Yn(Xn(u))<kn)return f>=An?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`};if(a<Vn||c<=0||Zn(d)>zn)return{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`};let p=0,m=0;for(let e=0;e<=c;e+=On){let t=Qn(this.microphoneHistory,this.referenceHistory,o,s-e,a,Dn);Math.abs(t)>Math.abs(m)&&(m=t,p=e)}let h=Math.max(0,p-On),g=Math.min(c,p+On);for(let e=h;e<=g;e+=1){let t=Qn(this.microphoneHistory,this.referenceHistory,o,s-e,a,2);Math.abs(t)>Math.abs(m)&&(m=t,p=e)}let _=s-p,v=Math.abs($n(this.microphoneHistory,this.referenceHistory,o,_,a)),y=Math.abs(m),b=0,x=0,S=0;for(let e=0;e<a;e+=1){let t=this.microphoneHistory[o+e]??0,n=this.referenceHistory[_+e]??0;b+=t*n,x+=n*n,S+=t*t}let C=Gn(x<=2**-52?0:b/x,0,Ln),w=0;for(let e=0;e<a;e+=1){let t=(this.microphoneHistory[o+e]??0)-C*(this.referenceHistory[_+e]??0);w+=t*t}let ee=S<=2**-52?0:w/S,T=new Float32Array(n.length),E=this.microphoneHistory.length-n.length,D=this.referenceHistory.length-n.length-p;for(let e=0;e<n.length;e+=1)T[e]=(this.microphoneHistory[E+e]??0)-C*(this.referenceHistory[D+e]??0);let O=qn(T),k=Yn(Xn(T));return m>=jn&&ee<=Fn?{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:m>=jn&&v<Mn&&ee>=In&&k>=An?{speechPcm:O,referenceActive:!0,speechDiscriminated:!0,state:`mixed`}:y<Nn&&v<Pn&&f>=An?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:v>=Mn?{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`}}resetCapture(){this.microphoneHistory=new Float32Array,this.referenceHistory=new Float32Array}reset(){this.references=[],this.resetCapture()}unavailable(e,t=Kn(e)){return this.microphoneHistory=Jn(this.microphoneHistory,t),this.referenceHistory=Jn(this.referenceHistory,new Float32Array(t.length)),{speechPcm:new Uint8Array(e),referenceActive:!1,speechDiscriminated:!1,state:`unavailable`}}renderReference(e,t){let n=new Float32Array(t),r=!1;for(let i of this.references){let a=i.startedAt+i.samples.length/N,o=Math.min(i.endedAt??a,a);e<o+Un&&e+t/16e3>=i.startedAt&&(r=!0);let s=Math.round((e-i.startedAt)*N),c=Math.round((o-i.startedAt)*N);for(let e=0;e<t;e+=1){let t=s+e;t<0||t>=c||(n[e]+=i.samples[t]??0)}}return{samples:n,tracked:r}}finishReference(e,t){let n=e.startedAt+e.samples.length/N;e.endedAt=Math.max(e.startedAt,Math.min(t,n));let r=Math.ceil((e.endedAt-e.startedAt)*N),i=Math.max(0,r-Hn-Vn);e.samples=new Float32Array(e.samples.subarray(i,r)),e.startedAt+=i/N}pruneReferences(e){this.references=this.references.filter(t=>t.endedAt===void 0||e<=t.endedAt+Un)}},nr=5e3,rr=class extends Error{};function ir(e){return typeof e==`object`&&!!e&&Number.isSafeInteger(e.id)}var ar=class{worker;onTerminalFailure;responseTimeoutMs;nextRequestId=0;generation=0;operation=Promise.resolve();pending=new Map;closed=!1;failure;constructor(e,t=()=>void 0,n=nr){this.worker=e,this.onTerminalFailure=t,this.responseTimeoutMs=n,e.onmessage=e=>{if(!ir(e.data)){this.failTerminal(Error(`Silero worker returned a malformed response.`));return}let t=this.pending.get(e.data.id);t!==void 0&&(e.data.error===void 0?(this.pending.delete(e.data.id),t.timer!==void 0&&clearTimeout(t.timer),t.resolve(e.data.result)):this.failTerminal(Error(e.data.error)))},e.onerror=e=>this.failTerminal(Error(e.message||`Silero worker failed.`))}async initialize(e){if(await this.enqueue(()=>this.request({type:`initialize`,modelUrl:e}))!==!0){let e=Error(`Silero worker returned an invalid initialization response.`);throw this.failTerminal(e),e}}async push(e){let t=this.generation,n=new Uint8Array(e),r;try{r=await this.enqueue(()=>this.request({type:`push`,pcm:n.buffer},[n.buffer],this.responseTimeoutMs))}catch(e){if(e instanceof rr)return[];throw e}if(t!==this.generation)return[];if(!Array.isArray(r))throw Error(`Silero worker returned invalid speech windows.`);return r}async reset(){this.generation+=1,await this.enqueue(()=>this.request({type:`reset`},void 0,this.responseTimeoutMs))}async close(){this.closed||(this.closed=!0,this.generation+=1,this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.failAll(Error(`Silero worker closed.`)))}enqueue(e){let t=this.operation.then(e,e);return this.operation=t,t}request(e,t,n){if(this.closed)return Promise.reject(this.failure??Error(`Silero worker is closed.`));let r=++this.nextRequestId;return new Promise((i,a)=>{let o={resolve:i,reject:a};n!==void 0&&(o.timer=setTimeout(()=>{this.pending.has(r)&&this.failTerminal(new rr(`Silero worker response timed out.`))},n)),this.pending.set(r,o),this.worker.postMessage({id:r,...e},t)})}failTerminal(e){this.closed||(this.failure=e,this.closed=!0,this.generation+=1,this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.failAll(e),this.onTerminalFailure())}failAll(e){for(let t of this.pending.values())t.timer!==void 0&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}},or=new URL(new URL(`../assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx`,import.meta.url).href,``+import.meta.url).href,sr=new URL(new URL(`../assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs`,import.meta.url).href,``+import.meta.url).href,cr=4096,lr=100,ur=`po-voice-capture`,dr=180,fr=5e3,pr=1e4,mr=.1,hr=10,K=2,gr=32767,_r=N*K*lr/1e3,vr=1e-8,yr=.05,br=N*300/1e3;function xr(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.samples instanceof Float32Array&&typeof t.capturedAt==`number`}function Sr(){return typeof window<`u`&&typeof window.speechSynthesis?.speak==`function`}function Cr(){return typeof AudioContext==`function`}function wr(){if(typeof SpeechSynthesisUtterance==`function`)return SpeechSynthesisUtterance;if(typeof window>`u`)return;let e=window.SpeechSynthesisUtterance;return typeof e==`function`?e:void 0}var Tr=class{sourceRate;sourceIndex=0;nextOutputAt=0;constructor(e){if(this.sourceRate=e,!Number.isFinite(e)||e<=0)throw Error(`Audio source rate must be positive.`)}push(e){let t=[],n=this.sourceRate/N;for(let r=0;r<e.length;r+=1){let i=this.sourceIndex+r;for(;this.nextOutputAt<=i;){let i=Math.max(-1,Math.min(1,e[r]??0));t.push(Math.round(i<0?i*32768:i*gr)),this.nextOutputAt+=n}}this.sourceIndex+=e.length;let r=new Uint8Array(t.length*2),i=new DataView(r.buffer);return t.forEach((e,t)=>i.setInt16(t*2,e,!0)),r}},Er=class{synthesis;utterance;playbackId;completion;requestedOutcome;settleCompletion;settled=!1;ducked=!1;fadeTimer;restoreTimer;startTimer;constructor(e,t,n){this.synthesis=e,this.utterance=t,this.playbackId=n,this.completion=new Promise(e=>{this.settleCompletion=e}),t.onstart=()=>{this.startTimer!==void 0&&clearTimeout(this.startTimer),this.startTimer=void 0},t.onend=()=>this.settle(this.requestedOutcome??`completed`),t.onerror=e=>this.settle(this.requestedOutcome??`failed`,e.error||`Browser speech synthesis failed.`),this.startTimer=setTimeout(()=>{this.synthesis.cancel(),this.settle(`failed`,`Browser speech synthesis did not start.`)},fr)}stop(e){this.settled||(this.requestedOutcome=e,this.synthesis.cancel(),this.settle(e))}duck(e,t,n){if(this.settled||this.ducked)return;this.ducked=!0;let r=Math.max(0,Math.min(1,e));this.fadeTo(r,Math.max(0,t),()=>{this.restoreTimer=setTimeout(()=>{this.restoreTimer=void 0,this.fadeTo(1,600,()=>{this.ducked=!1})},Math.max(0,n))})}fadeTo(e,t,n){this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.fadeTimer=void 0;let r=this.utterance.volume,i=Math.max(1,Math.ceil(t/50)),a=0,o=()=>{a+=1,this.utterance.volume=r+(e-r)*Math.min(1,a/i),!(a<i)&&(this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.fadeTimer=void 0,n())};t===0?o():this.fadeTimer=setInterval(o,t/i)}settle(e,t){this.settled||(this.settled=!0,this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.startTimer!==void 0&&clearTimeout(this.startTimer),this.fadeTimer=void 0,this.restoreTimer=void 0,this.startTimer=void 0,this.utterance.onstart=null,this.utterance.onend=null,this.utterance.onerror=null,this.settleCompletion({playbackId:this.playbackId,outcome:e,...t?{error:t}:{}}))}},Dr=class{context;playbackId;echoDiscriminator;completion;source;gain;settled=!1;settleCompletion;restoreTimer;startedAt;constructor(e,t,n,r){this.context=e,this.playbackId=n,this.echoDiscriminator=r,this.completion=new Promise(e=>{this.settleCompletion=e}),this.start(t)}stop(e){this.settled||(this.source!==void 0&&(this.source.onended=null),this.source?.stop(),this.settle(e))}duck(e,t,n){this.settled||this.gain===void 0||(this.gain.gain.value=Math.max(0,Math.min(1,e)),this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.restoreTimer=setTimeout(()=>{this.restoreTimer=void 0,this.gain!==void 0&&(this.gain.gain.value=1)},Math.max(0,n)))}async start(e){try{let t=await e;if(this.settled)return;if(t.byteLength===0||t.byteLength%K!==0)throw Error(`Streamed narration audio is empty or incomplete.`);if(this.context.state!==`running`)throw Error(`Browser audio playback is suspended. Tap the voice control.`);let n=new Float32Array(t.byteLength/K),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let e=0;e<n.length;e+=1)n[e]=r.getInt16(e*2,!0)/32768;let i=this.context.createBuffer(1,n.length,N);i.copyToChannel(n,0);let a=this.context.createBufferSource(),o=this.context.createGain();o.gain.value=1,a.buffer=i,a.onended=()=>this.settle(`completed`),a.connect(o),o.connect(this.context.destination),this.source=a,this.gain=o;let s=this.context.currentTime;this.startedAt=s,this.echoDiscriminator.beginPlayback(this.playbackId,i.getChannelData(0),s),a.start(s)}catch(e){let t=e instanceof Error?`${e.name}: ${e.message}`:String(e);this.settle(`failed`,t)}}settle(e,t){this.settled||(this.settled=!0,this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.source!==void 0&&(this.source.onended=null),this.startedAt!==void 0&&this.echoDiscriminator.endPlayback(this.playbackId,this.context.currentTime),this.source?.disconnect(),this.gain?.disconnect(),this.source=void 0,this.gain=void 0,this.settleCompletion({playbackId:this.playbackId,outcome:e,...t?{error:t}:{}}))}},Or=class{rebindProtocolSupported;microphoneConstraints;capabilities={capture:typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0,playback:Sr()||Cr(),captureActivity:!1,autonomousOrchestration:!1,playbackDucking:Sr()||Cr(),realtime:typeof RTCPeerConnection==`function`&&typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0};captureGeneration=0;captureDeviceId;constructor(e=!1,t=async()=>F){this.rebindProtocolSupported=e,this.microphoneConstraints=t}armUserGesture(){this.listenForMediaUnlock()}stream;context;workletInstalled=!1;activeCapture;activePlayback;speechDetector;preparingSpeechDetector;speechPreparation;listeningForMediaUnlock=!1;speechWarmup;speechWarmupTimer;echoDiscriminator=new tr;unlockMedia=()=>{if(typeof AudioContext<`u`)try{this.context??=new AudioContext;let e=this.context;e.resume().then(()=>{e.state===`running`&&this.stopListeningForMediaUnlock()}).catch(()=>void 0)}catch{}this.warmSpeechSynthesis()};async prepare(){this.armUserGesture(),this.speechPreparation??=this.prepareSpeechDetector(),await this.speechPreparation}createSpeechPresenceDetector(){return this.speechDetector}async startCapture(e){if(!this.capabilities.capture)throw Error(`This browser cannot capture microphone audio.`);if(this.activeCapture!==void 0)throw Error(`Browser microphone capture is already active.`);let t=this.captureGeneration,n=await this.microphoneConstraints();if(t!==this.captureGeneration)throw Error(`Microphone capture was cancelled.`);let r=n.audio.deviceId?.exact;if(this.stream&&this.captureDeviceId!==r){for(let e of this.stream.getTracks())e.stop();this.stream=void 0}if(this.stream??=await navigator.mediaDevices.getUserMedia(n),t!==this.captureGeneration){for(let e of this.stream.getTracks())e.stop();throw this.stream=void 0,Error(`Microphone capture was cancelled.`)}if(this.captureDeviceId=r,this.context??=new AudioContext,await this.context.resume(),this.context.state!==`running`)throw Error(`Browser audio capture is suspended. Tap the voice control and try again.`);this.stopListeningForMediaUnlock();let i=this.stream,a=this.context.createMediaStreamSource(i),o=this.context.createGain();o.gain.value=vr;let s=new Tr(this.context.sampleRate);this.echoDiscriminator.resetCapture();let c=[],l=0,u,d=0,f,p=0,m=t=>{let n=new Uint8Array(t),r=0;for(;r<t;){let e=c[0];if(e===void 0)break;let i=Math.min(e.byteLength,t-r);n.set(e.subarray(0,i),r),r+=i,i===e.byteLength?c.shift():c[0]=e.subarray(i)}l-=t;let i=t/K,a=(u??this.context.currentTime)+(d+i)/N;d+=i;let o=this.echoDiscriminator.process(n,a),s=p>0;p=Math.max(0,p-i),e(n,{speechPcm:s?new Uint8Array(n.byteLength):o.speechPcm,echoReferenceActive:o.referenceActive,echoDiscriminated:!s&&o.speechDiscriminated})},h=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)?t:void 0;n!==void 0&&f!==void 0&&Math.abs(n-f)>yr&&(this.echoDiscriminator.resetCapture(),p=l/K+br,u=n-(d+l/K)/N),n!==void 0&&(f=n+e.length/this.context.sampleRate),u??=n??this.context.currentTime-e.length/this.context.sampleRate;let r=s.push(e);if(r.byteLength!==0)for(c.push(r),l+=r.byteLength;l>=_r;)m(_r)},g,_;if(typeof AudioWorkletNode<`u`&&this.context.audioWorklet!==void 0){this.workletInstalled||=(await this.context.audioWorklet.addModule(yn),!0);let e=new AudioWorkletNode(this.context,ur);e.port.onmessage=e=>{xr(e.data)&&h(e.data.samples,e.data.capturedAt)},g=e,_=()=>{e.port.onmessage=null,e.port.close()}}else{let e=this.context.createScriptProcessor(cr,1,1);e.onaudioprocess=e=>h(e.inputBuffer.getChannelData(0),e.playbackTime),g=e,_=()=>{e.onaudioprocess=null}}a.connect(g),g.connect(o),o.connect(this.context.destination);let v=!1,y,b,x=new Promise((e,t)=>{y=e,b=t});for(let e of i.getTracks())e.onended=()=>b(Error(`The selected microphone was disconnected.`));let S={completion:x,stop:async()=>{if(!v){v=!0;for(let e of i.getTracks())e.onended=null;if(y(),_(),l>0&&m(l),a.disconnect(),g.disconnect(),o.disconnect(),!this.rebindProtocolSupported||this.stream!==i)for(let e of i.getTracks())e.stop();!this.rebindProtocolSupported&&this.stream===i&&(this.stream=void 0),this.activeCapture===S&&(this.activeCapture=void 0)}}};return this.activeCapture=S,S}speak(e,t){if(!this.capabilities.playback)throw Error(`This browser cannot play speech narration.`);this.activePlayback?.stop(`aborted`);let n;if(e.delivery===`streamed`){if(t===void 0)throw Error(`Streamed narration audio is unavailable.`);if(typeof AudioContext!=`function`)throw Error(`This browser cannot play streamed narration audio.`);if(this.context===void 0||this.context.state!==`running`)throw Error(`Browser audio playback is not unlocked. Tap the voice control and try again.`);n=new Dr(this.context,t,e.playbackId,this.echoDiscriminator)}else{this.finishSpeechWarmup(!1);let t=window.speechSynthesis,r=wr();if(r===void 0)throw Error(`This browser does not expose speech utterance playback.`);t.resume();let i=new r(e.text);e.rate!==void 0&&(i.rate=Math.max(mr,Math.min(hr,e.rate/dr))),e.voice&&(i.voice=t.getVoices().find(t=>t.name===e.voice||t.voiceURI===e.voice)??null),n=new Er(t,i,e.playbackId),t.speak(i)}return this.activePlayback=n,n.completion.finally(()=>{this.activePlayback===n&&(this.activePlayback=void 0)}),n}async close(){this.captureGeneration+=1;let e=this.speechDetector,t=this.preparingSpeechDetector,n=this.speechPreparation;this.speechDetector=void 0,this.preparingSpeechDetector=void 0,this.speechPreparation=void 0,this.capabilities.captureActivity=!1,this.capabilities.autonomousOrchestration=!1,await e?.close().catch(()=>void 0),t!==e&&await t?.close().catch(()=>void 0),await n?.catch(()=>void 0),this.stopListeningForMediaUnlock(),this.finishSpeechWarmup(!0),await this.activeCapture?.stop(),this.activePlayback?.stop(`aborted`);for(let e of this.stream?.getTracks()??[])e.stop();this.stream=void 0,this.context!==void 0&&this.context.state!==`closed`&&await this.context.close(),this.echoDiscriminator.reset(),this.context=void 0,this.workletInstalled=!1}listenForMediaUnlock(){this.listeningForMediaUnlock||typeof window>`u`||!this.capabilities.capture&&!this.capabilities.playback||(this.listeningForMediaUnlock=!0,window.addEventListener(`pointerdown`,this.unlockMedia,{capture:!0,passive:!0}),window.addEventListener(`keydown`,this.unlockMedia,{capture:!0}))}stopListeningForMediaUnlock(){this.listeningForMediaUnlock&&typeof window<`u`&&(this.listeningForMediaUnlock=!1,window.removeEventListener(`pointerdown`,this.unlockMedia,!0),window.removeEventListener(`keydown`,this.unlockMedia,!0))}warmSpeechSynthesis(){if(!Sr()||this.activePlayback!==void 0||this.speechWarmup!==void 0)return;let e=window.speechSynthesis,t=wr();if(t===void 0||(e.resume(),e.speaking||e.pending))return;let n=new t(`a`);n.volume=.01,n.rate=hr,n.onend=()=>this.finishSpeechWarmup(!1),n.onerror=()=>this.finishSpeechWarmup(!1),this.speechWarmup=n,this.speechWarmupTimer=setTimeout(()=>this.finishSpeechWarmup(!0),pr),e.speak(n)}finishSpeechWarmup(e){let t=this.speechWarmup;t!==void 0&&(this.speechWarmupTimer!==void 0&&clearTimeout(this.speechWarmupTimer),this.speechWarmupTimer=void 0,this.speechWarmup=void 0,t.onend=null,t.onerror=null,e&&window.speechSynthesis.cancel())}async prepareSpeechDetector(){if(typeof Worker>`u`||typeof WebAssembly>`u`)return;let e;try{if(e=new ar(new Worker(sr,{type:`module`,name:`po-silero-vad`}),()=>{(this.preparingSpeechDetector===e||this.speechDetector===e)&&(this.preparingSpeechDetector===e&&(this.preparingSpeechDetector=void 0),this.speechDetector===e&&(this.speechDetector=void 0),this.capabilities.captureActivity=!1,this.capabilities.autonomousOrchestration=!1)}),this.preparingSpeechDetector=e,await e.initialize(or),this.preparingSpeechDetector!==e){await e.close().catch(()=>void 0);return}this.preparingSpeechDetector=void 0,this.speechDetector=e,this.capabilities.captureActivity=!0,this.capabilities.autonomousOrchestration=this.rebindProtocolSupported}catch{this.preparingSpeechDetector===e&&(this.preparingSpeechDetector=void 0),this.speechDetector===e&&(this.speechDetector=void 0),await e?.close().catch(()=>void 0)}}};function kr(){let e=ke({header:_()});if(e.status!==`ok`||!e.metadata.instanceId)throw Error(`Voice requires the shell client instance identity.`);return e.metadata.instanceId}var Ar=`application/json`,jr=6e4,Mr=200,Nr=8e3,Pr=2e4;function Fr(e){return typeof e.eventEpoch==`string`&&e.eventEpoch.length>0&&e.eventEpoch.length<=Mr&&Number.isSafeInteger(e.heartbeatMs)&&(e.heartbeatMs??0)>0&&(e.heartbeatMs??0)<=jr?{eventEpoch:e.eventEpoch,heartbeatMs:e.heartbeatMs}:void 0}function q(e){return Object.assign(Error(e.error===``?`Voice media request failed with status ${String(e.status)}.`:e.error),{status:e.status,conflict:e.data})}function Ir(e){if(!e.ok)throw q(e);if(`standby`in e.data)throw Object.assign(Error(`Another client owns voice media for this session.`),{status:409,standby:!0,conflict:e.data.conflict});return e.data}async function Lr(e){let t=`Voice media request failed with status ${String(e.status)}.`,n;try{let r=await e.json();n=r,typeof r==`object`&&r&&`error`in r&&typeof r.error==`string`&&(t=r.error)}catch{}return Object.assign(Error(t),{status:e.status,conflict:n})}function J(e){return{method:`POST`,headers:{"content-type":Ar},body:JSON.stringify(e)}}function Rr(e,t={}){let n=new URL(e,`http://po.local`);for(let[e,r]of Object.entries(t))r!==void 0&&n.searchParams.set(e,String(r));return`${n.pathname}${n.search}`}function zr(e){try{e?.body?.cancel().catch(()=>void 0)}catch{}}async function Br(e,n,r,i,a,o=(e,n)=>t.fetch(e,n)){let s=new AbortController,c=a??s.signal,l,u=!1,d,f,p=new Promise((e,t)=>{f=t}),m=e=>{u||(u=!0,d=e,s.abort(e),zr(l),f(e))},h=()=>m(a?.reason??new DOMException(`Voice media control request was aborted.`,`AbortError`)),g=setTimeout(()=>m(Error(`Voice media control request timed out.`)),r);a?.addEventListener(`abort`,h,{once:!0});let _;try{_=o(e,{...n,signal:c})}catch(e){throw clearTimeout(g),a?.removeEventListener(`abort`,h),e}let v=_.then(async e=>{if(l=e,u)throw zr(e),d;return i(e)});try{return a?.aborted&&h(),await Promise.race([v,p])}finally{clearTimeout(g),a?.removeEventListener(`abort`,h)}}var Vr=class{sessionId;claimForActivation;takeoverGeneration;push;controlLocation;binding;constructor(e,t=!1,n){this.sessionId=e,this.claimForActivation=t,this.takeoverGeneration=n}media(){if(this.sessionId===null)throw Error(`PCM routes are session-scoped, not global live media.`);return H.session(this.sessionId)}remote(){return this.sessionId!==null&&/^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(this.sessionId)}async fetch(e,n,r={}){if(!this.remote())return t.fetch(n,r);let i=new Headers(r.headers),a=ke({header:_()});a.status===`ok`&&i.set(be,Oe(a.metadata));let o=new Request(new URL(e,`http://po.local`),{...r,headers:i}),s=new Uint8Array(await o.arrayBuffer()),c=new URL(o.url).searchParams.get(`connectionId`)??void 0;if(!c&&s.byteLength>0)try{let e=JSON.parse(new TextDecoder().decode(s));typeof e.connectionId==`string`&&(c=e.connectionId)}catch{c=void 0}if(!c)throw Error(`Paired Voice request has no connection binding.`);if(!this.binding||this.binding.connectionId!==c||this.binding.expiresAt<=Date.now()+Nr){let e=await V.host.relayBinding({body:{target:this.sessionId,connectionId:c}});if(!e.ok)throw q(e);let t=e.data;if(typeof t.binding!=`string`||!Number.isSafeInteger(t.expiresAt))throw Error(`Paired Voice media binding is invalid.`);this.binding={id:t.binding,connectionId:c,expiresAt:t.expiresAt}}let l=``;for(let e of s)l+=String.fromCharCode(e);let u=await V.host.relay({query:{binding:this.binding.id},body:{targetSessionId:``,method:o.method===`GET`?`GET`:`POST`,path:e,headers:[...o.headers.entries()],body:btoa(l)}});if(!u.ok)throw q(u);let d=u.data;if(!Number.isSafeInteger(d.status)||!Array.isArray(d.headers)||typeof d.body!=`string`)throw Error(`Paired Voice relay response is invalid.`);let f=atob(d.body),p=Uint8Array.from(f,e=>e.charCodeAt(0));return new Response(p.byteLength===0?null:p,{status:d.status,headers:d.headers})}async remoteResult(e,t,n){let r=await this.fetch(e,t,n),i;try{i=r.status===204?void 0:await r.json()}catch{i=void 0}return r.ok?{ok:!0,status:r.status,data:i,response:r}:{ok:!1,status:r.status,error:typeof i==`object`&&i&&`error`in i&&typeof i.error==`string`?i.error:`Voice media request failed with status ${String(r.status)}.`,data:i,response:r}}async connect(e,n,r){this.push=void 0;let i=t.active()?`remote`:`local`,a=this.claimForActivation;this.claimForActivation=!1;let o=this.takeoverGeneration;this.takeoverGeneration=void 0;let s=Ir(await this.declareClient(e,n,r,i,a,o));return this.controlLocation=i,this.push=this.sessionId===null?void 0:Fr(s),s}async refreshCapabilities(e,t,n){let r=this.controlLocation;if(r===void 0)throw Error(`Voice media client is not connected.`);let i=this.claimForActivation;this.claimForActivation=!1,Ir(await this.declareClient(e,t,n,r,i))}async disconnect(e,t){try{let n={clientId:e,connectionId:t},r=this.sessionId===null?await H.host.clientDisconnect({body:n}):this.remote()?await this.remoteResult(P.clientDisconnect,``,J(n)):await this.media().clientDisconnect({body:n});if(!r.ok&&r.status!==409)throw q(r)}finally{this.push=void 0,this.controlLocation=void 0,this.binding=void 0}}async nextEvent(e,t,n,r){let i=this.push,a=this.sessionId;if(i===void 0||a===null)return this.fetchEvent(e,t,n,r,!1);for(;!r.aborted;){let o=await st(a,i.eventEpoch,n,i.heartbeatMs,r);if(r.aborted)return;let s=o??await this.heartbeat(e,t);if(s.eventEpoch!==i.eventEpoch)throw Error(`Voice media broker changed.`);if(s.sequence<=n)continue;let c=await this.fetchEvent(e,t,n,r,!0);if(c===void 0)throw Error(`Voice media wake could not be resolved.`);return c}}declareClient(e,t,n,r,i=!1,a){let o={version:7,clientId:e,connectionId:t,clientKind:`browser`,controlLocation:r,capabilities:n,acceptStandby:!0,...i?{claimForActivation:!0}:{},...a===void 0?{}:{takeoverGeneration:a}};return this.sessionId===null?H.host.clientConnect({body:o}):this.remote()?this.remoteResult(P.clientConnect,``,J(o)):this.media().clientConnect({body:o})}async fetchEvent(e,t,n,r,i){let a=Rr(P.clientEvents,{clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}}),o={clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}},s=this.sessionId===null?H.host.clientEvents.url({query:o}):this.remote()?``:this.media().clientEvents.url({query:o});return Br(s,{},Nr,async e=>{if(e.status!==204){if(!e.ok)throw await Lr(e);return await e.json()}},r,(e,t)=>this.fetch(a,s,t))}heartbeat(e,t){let n=P.clientHeartbeat,r=this.sessionId===null?H.host.clientHeartbeat.url():this.remote()?``:this.media().clientHeartbeat.url();return Br(r,J({clientId:e,connectionId:t}),Nr,async e=>{if(!e.ok)throw await Lr(e);let t=ze(await e.json());if(t===null)throw Error(`Voice media heartbeat response is invalid.`);return t},void 0,(e,t)=>this.fetch(n,r,t))}async sendAudio(e,t,n,r,i){let a={clientId:e,connectionId:t,captureId:n},o={"content-type":Ae,...i===void 0?{}:{[je]:i.state,[Me]:String(i.levelDbfs),[Ne]:String(i.elapsedMs),...i.epoch===void 0?{}:{[Pe]:String(i.epoch)},...i.classifiedSpeechMs===void 0?{}:{[Fe]:String(i.classifiedSpeechMs)},...i.echoDiscriminatedSpeechMs===void 0?{}:{[Ie]:String(i.echoDiscriminatedSpeechMs)}}},s=new Blob([new Uint8Array(r)],{type:Ae}),c=this.remote()?await this.remoteResult(Rr(P.clientAudio,a),``,{method:`POST`,headers:o,body:s}):await this.media().clientAudio({query:a,headers:o,body:s});if(!c.ok)throw q(c)}async captureStopped(e,t,n,r){let i={clientId:e,connectionId:t,captureId:n,...r===void 0?{}:{error:r}},a=this.remote()?await this.remoteResult(P.clientCaptureStopped,``,J(i)):await this.media().clientCaptureStopped({body:i});if(!a.ok)throw q(a)}async receivePlaybackAudio(e,t,n,r){let i=[],a=0,o=Rr(P.clientPlaybackAudio,{clientId:e,connectionId:t,playbackId:n}),s=this.remote()?``:this.media().clientPlaybackAudio.url({query:{clientId:e,connectionId:t,playbackId:n}});for(;!r.aborted;){let e=await this.fetch(o,s,{signal:r});if(e.status===200&&e.headers.get(`content-type`)?.startsWith(`application/vnd.po.pcm-s16le`)){let t=new Uint8Array(await e.arrayBuffer());i.push(t),a+=t.byteLength}else{if(e.status===204&&e.headers.get(`x-po-playback-state`)===`sealed`){let e=new Uint8Array(a),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;return e}if(e.status!==204)throw await Lr(e)}}throw new DOMException(`Voice playback audio was aborted.`,`AbortError`)}async playbackFinished(e,t,n){let r={clientId:e,connectionId:t,...n},i=this.remote()?await this.remoteResult(P.clientPlaybackResult,``,J(r)):await this.media().clientPlaybackResult({body:r});if(!i.ok)throw q(i)}async realtimeNegotiate(e,t,n,r,i){let a=B.clientNegotiate,o=this.sessionId===null?H.host.realtimeNegotiate.url():this.remote()?``:this.media().realtimeNegotiate.url();return Br(o,J({clientId:e,connectionId:t,activationId:n,sdp:r}),Pr,async e=>{if(!e.ok)throw await Lr(e);let t=await e.json();if(typeof t!=`object`||!t||typeof t.sdp!=`string`)throw Error(`Realtime negotiation response is invalid.`);return t.sdp},i,(e,t)=>this.fetch(a,o,t))}async realtimeEvent(e,t,n,r){let i=this.sessionId===null?H.host.realtimeEvent.url():this.remote()?``:this.media().realtimeEvent.url();await this.postRealtime(B.clientEvent,i,{clientId:e,connectionId:t,activationId:n,event:r})}async realtimeState(e,t,n,r){let i=this.sessionId===null?H.host.realtimeState.url():this.remote()?``:this.media().realtimeState.url();await this.postRealtime(B.clientState,i,{clientId:e,connectionId:t,activationId:n,state:r})}postRealtime(e,t,n){return Br(t,J(n),Nr,async e=>{if(!e.ok)throw await Lr(e)},void 0,(n,r)=>this.fetch(e,t,r))}},Hr=class{device=new Or(!0,vn);clientId=kr();ownedSessionId=null;handoffActive=!1;releaseAudioPending=!1;selectionGeneration=0;client;globalClient;boundSessionId;operation=Promise.resolve();unsubscribe;closeOnPageHide=()=>this.close();closed=!1;openSession;constructor(){this.device.armUserGesture();let e=()=>this.select(L.store.state),t=L.store.subscribe(e),n=et.store.subscribe(e);this.unsubscribe=()=>{t.unsubscribe(),n.unsubscribe()},window.addEventListener(`pagehide`,this.closeOnPageHide,{once:!0}),this.select(L.store.state)}focus(e){}close(){if(this.closed)return;this.closed=!0,_n(),window.removeEventListener(`pagehide`,this.closeOnPageHide),this.unsubscribe(),this.client?.endRealtime(),this.globalClient?.endRealtime();let e=async()=>{try{await this.detach(),await this.globalClient?.stop(!1),this.globalClient=void 0}finally{await this.device.close()}};this.operation=this.operation.then(e,e).then(()=>void 0,()=>void 0)}async prepareLiveActivation(e){if(this.closed)throw Error(`Voice media page is closed.`);if(e!==void 0&&this.globalClient){let e=this.globalClient;this.globalClient=void 0,await e.stop(!1)}if(this.globalClient||this.startGlobalClient(!0,e),!this.globalClient)throw Error(`Global Voice media is unavailable.`);return this.globalClient.waitForConnection()}async prepareSessionActivation(e,t){if(this.closed)throw Error(`Voice media page is closed.`);if(await this.operation,(t!==void 0||R.store.state?.phase===`conflict`)&&await this.detach(),await this.attach(e,this.selectionGeneration,!0,t),!this.client)throw Error(`Session Voice media is unavailable.`);return this.client.waitForConnection()}startGlobalClient(e=!1,t){try{if(this.closed)return;let n={capabilities:{capture:!1,playback:!1,captureActivity:!1,autonomousOrchestration:!1,realtime:!0},async startCapture(){throw Error(`Global live Voice does not accept PCM capture.`)},speak(){throw Error(`Global live Voice does not accept PCM playback.`)},async close(){}},r;r=new cn(this.clientId,`global-${crypto.randomUUID()}`,new Vr(null,e,t),n,(e,n)=>{if(this.globalClient!==r)return;e===`conflict`&&this.reportOwnership(null,n,t);let i=R.store.state;i?.sessionId===null&&(e===`disconnected`&&i.realtime?.connection!==`failed`?R.reset():e!==`disconnected`&&R.update(()=>({...i,phase:e})))},(e,t)=>{if(this.globalClient!==r)return;if(e===void 0){if(R.store.state?.sessionId===null&&R.reset(),z.store.state?.sessionId===null&&z.reset(),t)return;this.globalClient=void 0,r.stop(!1);return}let n=R.store.state;R.update(()=>({sessionId:null,phase:n?.sessionId===null?n.phase:`connected`,realtime:e,realtimeOutputInterrupted:n?.sessionId===null?n.realtimeOutputInterrupted:void 0})),z.update(()=>({sessionId:null,mute:e=>this.controlGlobal(e?`mute`:`unmute`),interrupt:()=>{r.interruptRealtime(),this.controlGlobal(`interrupt`);let e=R.store.state;e?.sessionId===null&&R.update(()=>({...e,realtimeOutputInterrupted:!0}))},end:()=>{r.endRealtime(),this.controlGlobal(`end`)}}))},e=>new Rt(e,vn),e=>this.openSession?.(e)),this.globalClient=r,r.start()}catch(e){if(this.closed||R.store.state?.sessionId)return;let t=e instanceof Error?e.message:String(e);R.update(()=>({sessionId:null,phase:`conflict`,realtime:{connection:`failed`,listening:!1,speaking:!1,muted:!1,error:t}}))}}controlGlobal(e){V.host.liveControl({body:{action:e}}).then(e=>{if(!e.ok)throw Error(e.error)}).catch(e=>{let t=R.store.state;(t===void 0||t.sessionId===null)&&R.update(()=>({sessionId:null,phase:`conflict`,realtime:{connection:`failed`,listening:!1,speaking:!1,muted:!1,error:e instanceof Error?e.message:String(e)}}))})}select(e){let t=et.store.state,n=L.store.state;this.releaseAudioPending||=(this.ownedSessionId!==null||this.handoffActive)&&n===null&&t===void 0,this.ownedSessionId=n,this.handoffActive=t!==void 0;let r=++this.selectionGeneration;e??=(t?.phase===`rebinding`?t.targetSessionId:void 0)??t?.sourceSessionId??null,e!==this.boundSessionId&&t===void 0&&this.client?.endRealtime();let i=async()=>{this.closed||r!==this.selectionGeneration||(this.releaseAudioPending&&=(await this.detach(),await this.device.close(),!1),!(this.closed||r!==this.selectionGeneration)&&(e===null?await this.detach():await this.attach(e,r)))};this.operation=this.operation.then(i,i).then(()=>void 0,()=>void 0)}async attach(e,t,n=!1,r){if(this.client!==void 0&&this.boundSessionId===e||(await this.detach(),this.closed||t!==this.selectionGeneration))return;let i;i=new cn(this.clientId,`connection-${crypto.randomUUID()}`,new Vr(e,n,r),this.device,(t,n)=>{this.client===i&&this.boundSessionId===e&&(t===`disconnected`?R.store.state?.sessionId===e&&R.reset():(R.update(n=>n?.sessionId===null&&n.realtime!==void 0&&n.realtime.connection!==`failed`?n:n?.sessionId===e?{...n,phase:t}:{sessionId:e,phase:t}),t===`conflict`?this.reportOwnership(e,n,r):t===`connected`&&R.update(t=>t?.sessionId===e?{...t,ownership:void 0,ownershipConflict:void 0,actions:void 0}:t)))},t=>{if(this.client!==i||this.boundSessionId!==e)return;let n=R.store.state;n?.sessionId===e&&R.update(()=>({...n,...t===void 0?{}:{realtime:t},...t===void 0?{realtime:void 0,realtimeOutputInterrupted:void 0}:{}}))},e=>new Rt(e,vn)),this.client=i,this.boundSessionId=e,z.store.state?.sessionId!==null&&z.update(()=>({sessionId:e,mute:e=>i.muteRealtime(e),interrupt:()=>{i.interruptRealtime();let t=R.store.state;t?.sessionId===e&&R.update(()=>({...t,realtimeOutputInterrupted:!0}))},end:()=>i.endRealtime()})),i.start()}reportOwnership(e,t,n){let r=t instanceof Error&&`conflict`in t?t.conflict:void 0;if(r?.code!==`VOICE_OWNERSHIP_CONFLICT`)return;let i=ke({header:_()}),a=i.status===`ok`&&i.metadata.deviceId===r.owner.deviceId;R.update(t=>({...t?.sessionId===e?t:{sessionId:e,phase:`conflict`},ownership:{kind:n===void 0?a?`standby`:`conflict`:`stale`,ownerName:r.owner.deviceName,deviceName:i.status===`ok`?i.metadata.deviceName:void 0},ownershipConflict:r,actions:{takeOver:()=>{this.retryOwnership(e,r.owner.generation)},retry:()=>{this.retryOwnership(e)}}}))}async retryOwnership(e,t){try{if(e===null){let e=this.globalClient;this.globalClient=void 0,await e?.stop(!1),this.startGlobalClient(!0,t)}else await this.prepareSessionActivation(e,t)}catch(n){this.reportOwnership(e,n,t)}}async detach(){let e=this.client,t=this.boundSessionId;this.client=void 0,this.boundSessionId=void 0,t!==void 0&&R.store.state?.sessionId===t&&R.reset(),t!==void 0&&z.store.state?.sessionId===t&&z.reset(),await e?.stop(!1)}};function Ur(e){let t=tt.store.state;return t===void 0&&(t=new Hr,tt.update(()=>t)),e.mount?.scope===`session`&&t.focus(e.mount.sessionId),e.openSession&&(t.openSession=t=>e.openSession?.(t)),()=>void 0}var Wr=u(Ur),Gr={id:`voice`,label:`voice`,detail:`Speak requests and hear Po narrate its work. Available voice features depend on the session host.`,order:60,groups:[{id:`start`,label:`New sessions start with`,detail:`Press v e in a session to start voice.`},{id:`live`,label:`Live conversation`,detail:`Live handles the talking. Po still does the work in your session.`,signInProvider:`po-chatgpt`},{id:`daily`,label:`Daily work`,detail:`Listens with the session host’s transcriber. Dictation from the composer uses the same transcriber.`},{id:`narration`,label:`Narration`,detail:`How daily work corrects what it heard and speaks back.`}],fields:[{id:`mode`,localOnly:!0,label:`New sessions start with`,kind:`select`,keyPath:[`voice`,`mode`],group:`start`,presentation:`cards`,defaultValue:`legacy`,options:[{value:`live`,label:`Live conversation`,detail:`Experimental. Back-and-forth talk that answers as you speak. Best for thinking out loud with Po.`},{value:`legacy`,label:`Daily work`,detail:`Say a request, Po transcribes it and narrates as it works. Best while Po is busy.`}]},{id:`live-voice`,localOnly:!0,label:`Voice`,kind:`select`,keyPath:[`voice`,`live`,`voice`],group:`live`,placeholder:`Default (cove)`,options:[`juniper`,`maple`,`spruce`,`ember`,`vale`,`breeze`,`arbor`,`sol`,`cove`,`aube`,`bubbie`,`haetsal`,`hanul`,`himari`,`leher`,`miko`,`neer`,`porto`,`rindo`,`rio`,`rivage`,`selva`,`sonna`,`tinta`,`viola`].map(e=>({value:e,label:e}))},{id:`live-model`,localOnly:!0,label:`Model`,kind:`text`,keyPath:[`voice`,`live`,`model`],group:`live`,placeholder:`gpt-live-1-codex`},{id:`engine`,localOnly:!0,label:`Transcriber`,kind:`select`,keyPath:[`voice`,`engine`],group:`daily`,detail:`Auto uses the first one it finds.`,options:[`auto`,`whisper-cpp`,`openai-whisper`,`mlx-whisper`].map(e=>({value:e,label:e}))},{id:`language`,label:`Language`,kind:`text`,keyPath:[`voice`,`language`],group:`daily`,placeholder:`en`},...[`whisper-cpp`,`openai-whisper`,`mlx-whisper`].flatMap(e=>[{id:`${e}-binary`,localOnly:!0,label:`${e} executable`,kind:`text`,keyPath:[`voice`,`adapters`,e,`binary`],group:`daily`},{id:`${e}-model`,localOnly:!0,label:`${e} model`,kind:`text`,keyPath:[`voice`,`adapters`,e,`model`,e===`whisper-cpp`?`path`:`id`],group:`daily`}]),{id:`correction-model`,label:`Correction and narration model`,kind:`select`,optionsFrom:`models`,keyPath:[`voice`,`autoCapture`,`model`],group:`narration`},{id:`endpoint`,label:`Silence before sending (ms)`,kind:`number`,keyPath:[`voice`,`autoCapture`,`utteranceIdleMs`],group:`daily`},{id:`transcription-timeout`,label:`Transcription timeout (ms)`,kind:`number`,keyPath:[`voice`,`autoCapture`,`transcriptionTimeoutMs`],group:`daily`},{id:`narration-engine`,localOnly:!0,label:`Narration engine`,kind:`select`,keyPath:[`voice`,`autoCapture`,`tts`,`engine`],group:`narration`,options:[{value:`macos-say`,label:`macOS say`}]},{id:`narration-voice`,localOnly:!0,label:`Narration voice`,kind:`text`,keyPath:[`voice`,`autoCapture`,`tts`,`voice`],group:`narration`},{id:`narration-rate`,localOnly:!0,label:`Narration rate`,kind:`number`,keyPath:[`voice`,`autoCapture`,`tts`,`rate`],group:`narration`}]},Kr=n({...Gr,icon:ye}),qr=n({...Gr,icon:ye}),Jr=T({name:`voice`,keys:`v e`,statusKey:`po-voice`,activeSource:rt,hideWhenEmpty:!0,marksBackgroundWork:!1,placement:`bottom`,order:60}),Yr=i(at),Xr=i(ot),Zr=ue({data:it}),Qr=ue({slot:`activity.voice`,id:`voice`,component:At}),$r=1e3,ei=100,ti=1e4,ni=3e3,ri=.01,ii=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`],ai=class{startedAt;lastSpeechAt;get speechDetected(){return this.lastSpeechAt!==void 0}observe(e,t){this.startedAt??=t;let n=0;for(let t of e)n+=t*t;if((e.length===0?0:Math.sqrt(n/e.length))>=ri)return this.lastSpeechAt=t,!1;let r=this.lastSpeechAt??this.startedAt,i=this.speechDetected?ni:ti;return t-r>=i}};function oi(e,t){let n=globalThis.AudioContext;if(n===void 0)return()=>void 0;let r,i,a;try{r=new n,i=r.createMediaStreamSource(e);let o=r.createAnalyser();o.fftSize=2048,o.smoothingTimeConstant=.2,i.connect(o);let s=new Float32Array(o.fftSize),c=new ai;a=setInterval(()=>{o.getFloatTimeDomainData(s),c.observe(s,Date.now())&&t(c.speechDetected)},ei),r.resume().catch(()=>void 0)}catch{return i?.disconnect(),r?.close().catch(()=>void 0),()=>void 0}return()=>{a!==void 0&&clearInterval(a),i?.disconnect(),r?.close().catch(()=>void 0)}}function si(){let e=globalThis,t=e.MediaRecorder,n=e.navigator?.mediaDevices;if(t===void 0||n===void 0)throw Error(`This browser cannot record microphone audio.`);return{getUserMedia:async()=>await n.getUserMedia(F),createRecorder:(e,n)=>new t(e,n),isTypeSupported:e=>t.isTypeSupported(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),now:()=>Date.now(),watchSilence:oi}}async function ci(e){e??=si();let t=ii.find(t=>e.isTypeSupported(t)),n=await e.getUserMedia(),r;try{r=e.createRecorder(n,t===void 0?void 0:{mimeType:t})}catch(e){for(let e of n.getTracks())e.stop();throw e}let i=[],a=0,o,s=!1,c=!1,l=!1,u=0,d=()=>void 0,f=()=>void 0,p=()=>void 0,m=new Promise((e,t)=>{f=e,p=t}),h=()=>{e.clearTimer(y),d(),r.ondataavailable=null,r.onerror=null,r.onstop=null;for(let e of n.getTracks())e.onended=null,e.stop()},g=(t,n)=>{s||(s=!0,h(),n===void 0?f(c||t===void 0?void 0:{audio:t,durationMs:Math.min(ut,Math.max(0,Math.round(e.now()-u)))}):p(n))},_=()=>{let e=r.mimeType||i.find(e=>e.type.length>0)?.type||``;return new Blob(i,{type:e})},v=()=>{if(!(s||l)&&r.state!==`inactive`){l=!0;try{r.stop()}catch(e){g(void 0,e instanceof Error?e:Error(`Browser audio recording failed.`))}}},y=e.setTimer(v,ut);for(let e of n.getTracks())e.onended=()=>g(void 0,Error(`The selected microphone was disconnected.`));r.ondataavailable=e=>{if(s||c||o!==void 0||e.data.size===0)return;let t=a+e.data.size;t>4194304?(o=Error(`The recording exceeds the 4 MiB transcription limit.`),v()):(a=t,i.push(e.data))},r.onerror=e=>g(void 0,o??e.error??Error(`Browser audio recording failed.`)),r.onstop=()=>g(o===void 0?_():void 0,o);try{u=e.now(),r.start($r);let t=e.watchSilence?.(n,e=>{e||(c=!0),v()});t!==void 0&&(d=t,s&&d())}catch(e){g(void 0,e instanceof Error?e:Error(`Browser audio recording failed.`)),await m}return{result:m,stop:v,cancel:()=>{c=!0,v()}}}function li(e){if(typeof e!=`object`||!e||!(`transcript`in e))return;let t=e.transcript;return typeof t==`string`?t:void 0}async function ui(e,t,n,r){if(e.size===0)throw Error(`The recording is empty.`);if(e.size>4194304)throw Error(`The recording exceeds the 4 MiB transcription limit.`);if(!Number.isSafeInteger(n)||n<0||n>3e5)throw Error(`The recording duration is invalid.`);let i=await H.session(t).manualTranscribe({headers:{"content-type":e.type,[lt]:String(n)},body:e,...r===void 0?{}:{signal:r}}),a=li(i.data);if(!i.ok)throw Error(i.error===``?`Voice transcription failed with status ${String(i.status)}.`:i.error);if(a===void 0)throw Error(`Voice transcription returned an invalid response.`);return a}var di={start:ci,transcribe:async(e,t,n,r)=>await ui(e,t,n,r)},fi=class{append;changed;dependencies;state={phase:`idle`};recording;transcription;generation=0;constructor(e,t,n=di){this.append=e,this.changed=t,this.dependencies=n}snapshot(){return this.state}setAppend(e){this.append=e}reset(){this.invalidate(),this.publish({phase:`idle`})}dispose(){this.invalidate(),this.state={phase:`idle`}}async toggle(e){if(e===null||this.state.phase===`starting`||this.state.phase===`transcribing`)return;if(this.state.phase===`recording`){this.publish({phase:`transcribing`}),this.recording?.stop();return}let t=this.append,n=++this.generation;this.publish({phase:`starting`});try{let r=await this.dependencies.start();if(this.generation!==n){r.cancel();return}this.recording=r,this.publish({phase:`recording`}),this.finish(r,n,e,t)}catch(e){if(this.generation!==n)return;this.publish({phase:`idle`,error:e instanceof Error?e.message:`Voice recording failed.`})}}async finish(e,t,n,r){let i;try{let a=await e.result;if(this.generation!==t)return;if(a===void 0){this.recording=void 0,this.publish({phase:`idle`});return}this.recording===e&&(this.recording=void 0),this.publish({phase:`transcribing`}),i=new AbortController,this.transcription=i;let o=await this.dependencies.transcribe(a.audio,n,a.durationMs,i.signal);if(this.generation!==t)return;r(o),this.publish({phase:`idle`})}catch(n){if(this.generation!==t)return;this.recording===e&&(this.recording=void 0),this.publish({phase:`idle`,error:n instanceof Error?n.message:`Voice recording failed.`})}finally{i!==void 0&&this.transcription===i&&(this.transcription=void 0)}}invalidate(){this.generation+=1,this.recording?.cancel(),this.recording=void 0,this.transcription?.abort(),this.transcription=void 0}publish(e){this.state=e,this.changed()}},pi=`manual voice is unavailable while autonomous voice is active`;function mi({error:e,onDismiss:t,children:n}){return p(g,{open:e!==void 0,onOpenChange:e=>{e||t()},children:[l(y,{asChild:!0,children:n}),p(c,{side:`top`,align:`end`,sideOffset:8,collisionPadding:12,role:`alert`,"data-testid":`composer-voice-error`,onOpenAutoFocus:e=>e.preventDefault(),className:`w-64 flex-row items-start gap-2 border-po-edge-red bg-po-tint-red p-2.5 text-sm leading-relaxed text-po-red`,children:[l(fe,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),l(`span`,{className:`min-w-0 flex-1 break-words`,children:e}),l(S,{"aria-label":`dismiss`,className:`shrink-0 rounded-sm p-0.5 hover:bg-po-tint-red`,children:l(x,{"aria-hidden":!0,className:`size-3.5`})})]})]})}function hi({sessionId:t,appendComposerDraft:n,statuses:r,registeredModes:i}){let a=w(L.store,e=>e),o=w(R.store),c=xt(r[`po-voice`]),[u,d]=M({phase:`idle`}),p=f(void 0);p.current??=new fi(n,()=>{d(p.current?.snapshot()??{phase:`idle`})});let m=u.phase,h=u.error,g=o?.sessionId===null&&o.realtime!==void 0&&o.realtime.connection!==`closed`,_=c.mode===`auto`||c.mode===`live`||a!==null||g;s(()=>{let e=p.current;return()=>e?.dispose()},[]),s(()=>{p.current?.setAppend(n)},[n]),s(()=>{p.current?.reset()},[t,_]);let v=()=>{_||p.current?.toggle(t)},y=!_&&m===`recording`,b=_?pi:h??(y?`stop voice recording and fill the prompt`:m===`transcribing`?`transcribing voice recording`:m===`starting`?`starting voice recording`:`start voice recording`),x=_?`blocked`:m,S=h&&!_?`text-po-red`:`text-po-dim`;return i?.includes(`voice-auto`)?l(mi,{error:_?void 0:h,onDismiss:()=>p.current?.reset(),children:l(e,{variant:y?`danger-outline`:`ghost`,size:`icon-md`,"data-testid":`composer-voice-action`,"data-voice-mode":_?`auto`:y?`manual`:`off`,"data-voice-phase":x,"aria-label":b,title:b,disabled:t===null||_||m===`starting`||m===`transcribing`,onClick:v,className:`shrink-0 ${S}`,children:y?l(C,{className:`size-3 fill-current`}):m===`starting`||m===`transcribing`?l(ae,{className:`size-4 animate-spin`}):l(h&&!_?fe:ye,{className:`size-4`})})}):null}var gi=ue({slot:`composer-actions`,id:`voice`,component:hi});function _i(e){let t=t=>e[t]?.label||`Microphone`;return e.map((n,r)=>e.some((e,n)=>n!==r&&t(n)===t(r))?`${t(r)} · ${n.deviceId.slice(0,6)}`:t(r))}function vi(){let{inputs:t,choice:n}=w(G.store,e=>e),[i,a]=M(0);if(n===void 0)return null;let s=_i(t),c=i<s.length?i:0,u=e=>{let r=t[s.indexOf(e)];r!==void 0&&n(r.deviceId,!0)};return l(O,{open:!0,onOpenChange:e=>{e||n(null,!1)},children:p(d,{width:`sm`,"data-testid":`voice-microphone-dialog`,"aria-describedby":void 0,onKeyDown:e=>he(e,{options:s,cursor:c,onCursorChange:a,onSelect:u}),children:[l(te,{children:l(re,{children:`choose a microphone`})}),p(o,{children:[l(me,{children:`autonomous voice found more than one input. this browser remembers the one you pick.`}),l(r,{options:s,cursor:c,onCursorChange:a,onSelect:u,testIdPrefix:`voice-microphone-option`}),p(ne,{className:`flex-col items-stretch`,children:[p(`span`,{className:`w-full text-sm text-po-dim`,children:[ve(s.length),` · esc uses the browser default once`]}),l(e,{variant:`outline`,size:`md`,"data-testid":`voice-microphone-default`,onClick:()=>n(null,!0),children:`always use browser default`})]})]})]})})}var yi=ue({slot:`overlay`,id:`voice`,component:vi}),bi=v({id:`voice.toggle`,path:[{key:`v`,label:`voice`,detail:`autonomous voice capture`},{key:`e`,label:`toggle`,detail:`start or stop autonomous capture`}],command:`mode voice-auto`}),xi=u(Ur),Si=b({name:`voice`,modeId:`voice-auto`,keys:`v e`,icon:ye,statusKey:`po-voice`,order:60}),Ci=`describe_voice_tools`,wi=`use_voice_tools`,Ti=`narrate`,Ei=`transfer_voice`,Di=6,Oi=8,ki=72,Ai={tone:`error`,glyph:`✗`,label:`failed`},ji={playing:{tone:`warning`,glyph:`◐`,label:`playing`},completed:{tone:`success`,glyph:`✓`,label:`completed`},interrupted:{tone:`warning`,glyph:`⊘`,label:`interrupted`},superseded:{tone:`dim`,glyph:`○`,label:`superseded`},failed:Ai,rejected:{tone:`error`,glyph:`✗`,label:`rejected`},cancelled:{tone:`warning`,glyph:`⊘`,label:`cancelled`},stopped:{tone:`warning`,glyph:`■`,label:`stopped`},not_executed:{tone:`dim`,glyph:`○`,label:`not executed`},preflight_failed:{tone:`error`,glyph:`✗`,label:`preflight failed`}};function Y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function X(e){return e!==void 0}function Mi(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e<=31||e===127?` `:n}return t.replace(/\s+/gu,` `).trim()}function Z(e,t){let n=e?.[t];return typeof n==`string`&&Mi(n)||void 0}function Ni(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Pi(e){return e?e.content.flatMap(e=>{let t=Y(e);return t?.type===`text`&&typeof t.text==`string`?[t.text]:[]}):[]}function Fi(e){if(e)try{return Y(JSON.parse(e))}catch{return}}function Ii(e){return Y(e?.details)??Fi(Pi(e)[0])}function Li(e,t,n=`${t}s`){return e===1?t:n}function Q(e,t,n={}){return{text:e,tone:t,...n}}function Ri(e){let t=e.names;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function zi(e){let t=e.calls;return Array.isArray(t)?t.map(Y).filter(X):[]}function Bi(e,t){if(e===`narrate`){let e=typeof t.text==`string`?Mi(t.text):``,n=e.length>ki?`${e.slice(0,69)}…`:e;return{action:`narrate`,...n?{detail:n}:{},detailIsName:!1}}if(e===`transfer_voice`){let e=Ni(t,`target`);return{glyph:`↪`,action:`hand off`,...e===void 0?{}:{detail:`target ${e}`},detailIsName:!1}}if(e===`describe_voice_tools`){let e=Ri(t);return e.length===1?{glyph:`☰`,action:`discover`,detail:e[0],detailIsName:!0}:e.length>1?{glyph:`☰`,action:`discover`,detail:`· ${e.length} capabilities`,detailIsName:!1}:{glyph:`☰`,action:`discover`,detailIsName:!1}}let n=zi(t);if(n.length===1){let e=Z(n[0],`name`);return{glyph:`▶`,action:`run`,...e?{detail:e}:{},detailIsName:e!==void 0}}return n.length>1?{glyph:`▶`,action:`run`,detail:`· ${n.length} capabilities`,detailIsName:!1}:{glyph:`▶`,action:`run`,detailIsName:!1}}function Vi(e){let t=e.enum;if(Array.isArray(t)){let e=t.filter(e=>[`string`,`number`,`boolean`].includes(typeof e));if(e.length>0)return e.join(` | `)}let n=e.const;if([`string`,`number`,`boolean`].includes(typeof n))return String(n);let r=e.type;if(typeof r==`string`)return r;if(Array.isArray(r))return r.filter(e=>typeof e==`string`).join(` | `);if(Array.isArray(e.anyOf)){let t=e.anyOf.map(Y).filter(X).map(Vi).filter(Boolean);if(t.length>0)return t.join(` | `)}return`value`}function Hi(e){let t=Y(e),n=Y(t?.properties);if(!t||!n)return;let r=new Set(Array.isArray(t.required)?t.required.filter(e=>typeof e==`string`):[]),i=Object.entries(n).map(([e,t])=>{let n=Y(t),i=n?Vi(n):`value`;return`${e}${r.has(e)?``:`?`}: ${i}`});return i.length>0?i.join(`, `):`{}`}function Ui(e,t){let n=e.enabled===!0,r=Z(e,`name`)??`capability`,i=Z(e,`label`)??r,a=[Q(`${n?`●`:`○`} ${i} · ${r}${n?``:` · disabled`}`,n?`text`:`dim`)];if(!t)return a;let o=Z(e,`description`),s=Hi(e.inputSchema);return o&&a.push(Q(o,`muted`,{indent:!0})),s&&a.push(Q(`input ${s}`,`dim`,{indent:!0})),a}function Wi(e,t){let n=Array.isArray(e.tools)?e.tools.map(Y).filter(X):[],r=Array.isArray(e.conflicts)?e.conflicts.map(Y).filter(X):[],i=Array.isArray(e.unknownNames)?e.unknownNames.filter(e=>typeof e==`string`):[],a=Ni(e,`catalogRevision`),o=`${n.length} voice ${Li(n.length,`capability`,`capabilities`)}${a===void 0?``:` · catalog rev ${a}`}`,s=t?n:n.slice(0,Di),c=[Q(o,`muted`),...s.flatMap(e=>Ui(e,t))],l=n.length-s.length;l>0&&c.push(Q(`… ${l} more`,`dim`)),n.length===0&&c.push(Q(`No voice capabilities are currently registered.`,`dim`));for(let e of r){let t=Z(e,`name`)??`capability`,n=Z(e,`message`)??`Conflicting registrations.`;c.push(Q(`! ${t} · ${n}`,`warning`))}return i.length>0&&c.push(Q(`? Unknown: ${i.join(`, `)}`,`warning`)),c}function Gi(e){if(typeof e==`string`)return Mi(e);if(typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`)return String(e);if(e===null)return`null`;if(Array.isArray(e)){let t=e.map(Gi);return t.every(e=>e!==void 0)?t.join(`, `)||`none`:void 0}}function Ki(e){let t=Gi(e);if(t!==void 0)return[Q(t,`text`,{indent:!0})];let n=Y(e);return n?Object.entries(n).flatMap(([e,t])=>{let n=Gi(t);return n===void 0?[]:[Q(`${e} ${n}`,`text`,{indent:!0})]}):[]}function qi(e){return Z(Y(e.error),`message`)}function Ji(e,t){let n=Z(e,`name`)??`capability`,r=Z(e,`status`)??`failed`,i=ji[r]??Ai,a=qi(e),o=[Q(`${i.glyph} ${n} · ${i.label}${a?` · ${a}`:``}`,i.tone)];return r===`completed`&&(t||e.result!==void 0)&&o.push(...Ki(e.result)),o}function Yi(e,t){let n=Array.isArray(e.results)?e.results.map(Y).filter(X):[],r=Array.isArray(e.errors)?e.errors.map(Y).filter(X):[],i=ji[Z(e,`status`)??`failed`]??Ai,a=`${i.glyph} Voice batch ${i.label} · ${n.length} ${Li(n.length,`call`)}`,o=t?n:n.slice(0,Oi),s=[Q(a,i.tone,{bold:!0}),...o.flatMap(e=>Ji(e,t))],c=n.length-o.length;c>0&&s.push(Q(`… ${c} more`,`dim`));for(let e of r){let t=Z(e,`message`);t&&!n.some(e=>qi(e)===t)&&s.push(Q(`✗ ${t}`,`error`))}return s}function Xi(e){let t=Y(e.error);if(t)return[Q(`✗ ${Z(t,`message`)??`Voice capability failed.`}${t.retryable===!0?` · retryable`:``}`,`error`)]}function Zi(e,t){let n=Mi(Pi(e)[0]??(t.isPartial?`running`:`No result details.`)),r=t.isPartial?`◐`:t.isError?`✗`:`✓`,i=t.isPartial?`warning`:t.isError?`error`:`muted`;return[Q(`${r} ${n}`,i)]}function Qi(e,t){let n=Ii(e),r=n?Xi(n):void 0;if(r)return r;let i=Z(n,`outcome`)??(t.isPartial?`playing`:void 0);if(!i)return Zi(e,t);let a=ji[i]??Ai;return[Q(`${a.glyph} Narration ${a.label}`,a.tone)]}function $i(e){let t=Z(e,`state`),n=Z(e,`mode`);if(!t||!n||typeof e.muted!=`boolean`)return;let r=Z(e,`manual`),i=Z(e,`error`);return{state:t,phase:t===`active`?`active`:t===`starting`||t===`stopping`?`pending`:`idle`,mode:n,muted:e.muted,...r?{manual:r}:{},...i?{error:i}:{}}}function ea(e){return Object.entries(e).flatMap(([e,t])=>{let n=Gi(t);if(n!==void 0)return[{key:e,value:n||`empty`}];if(Array.isArray(t))return[{key:e,value:`${t.length} ${Li(t.length,`item`)}`}];let r=Y(t);if(!r)return[];let i=Object.keys(r).length;return[{key:e,value:`${i} ${Li(i,`field`)}`}]})}function ta(e,t,n){let r=e===`narrate`?void 0:Ii(t);if(!(!r||Y(r.error)!==void 0||e===`describe_voice_tools`&&Array.isArray(r.tools)||e===`use_voice_tools`&&Array.isArray(r.results))){let e=$i(r);return e?{kind:`status`,status:e}:{kind:`fields`,fields:ea(r)}}return{kind:`lines`,lines:ia(e,t,n)}}function na(e){return typeof e.text==`string`?e.text.normalize(`NFKC`).replace(/\s+/gu,` `).trim():``}function ra(e){return Z(Y(Ii(e)?.error),`message`)||Mi(Pi(e)[0]??``)}function ia(e,t,n){if(e===`narrate`)return Qi(t,n);let r=Ii(t);return(r?Xi(r):void 0)||(e===`describe_voice_tools`&&r&&Array.isArray(r.tools)?Wi(r,n.expanded):e===`use_voice_tools`&&r&&Array.isArray(r.results)?Yi(r,n.expanded):Zi(t,n))}function aa({toolName:e,args:t,result:n,running:r,isError:i}){if(e===`narrate`){let e=na(t);return p(`div`,{role:`group`,"aria-label":`narration`,"data-testid":`narration-message`,"data-narration-state":r?`playing`:i?`failed`:`complete`,className:`flex min-w-0 items-start gap-2 text-base text-po-text`,children:[l(le,{"aria-hidden":`true`,className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-po-magenta`}),l(`p`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:e||`Narration unavailable.`})]})}let o=Bi(e,t),s=ia(e,n,{expanded:!1,isError:i,isPartial:r}),c=ia(e,n,{expanded:!0,isError:i,isPartial:r}),u=ta(e,n,{expanded:!1,isError:i,isPartial:r}),d=i?ra(n):``;return l(de,{tone:h({running:r,isError:i}),expandable:!i&&c.length>s.length,children:({expanded:t})=>p(a,{children:[l(se,{title:e,children:p(`span`,{"data-testid":`tool-call-${e}`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[p(`span`,{className:`shrink-0 font-semibold text-po-hi`,children:[o.glyph,` `,o.action]}),o.detail?l(`span`,{className:`min-w-0 truncate ${o.detailIsName?`text-po-blue`:`text-po-dim`}`,children:o.detail}):null]})}),i?d.length>0?l(ce,{"data-testid":`tool-result-${e}`,children:l(`p`,{className:`whitespace-pre-wrap break-words text-po-red`,children:d})}):null:l(ce,{"data-testid":`tool-result-${e}`,children:r&&n===null?l(ie,{tone:`running`,children:`running`}):u.kind===`status`?l(sa,{status:u.status}):u.kind===`fields`?l(ca,{fields:u.fields}):l(ge,{lines:t?c:s})})]})})}var oa={active:`green`,pending:`yellow`,idle:`neutral`};function sa({status:e}){return p(`div`,{className:`flex flex-col gap-2`,children:[p(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(A,{tone:oa[e.phase],children:`voice ${e.state}`}),l(A,{tone:`blue`,children:`mode ${e.mode}`}),l(A,{tone:e.muted?`yellow`:`neutral`,children:e.muted?`mic muted`:`mic on`}),e.manual===void 0?null:l(A,{children:`dictation ${e.manual}`})]}),e.error===void 0?null:l(`p`,{className:`break-words text-po-red`,children:e.error})]})}function ca({fields:e}){return e.length===0?l(`p`,{className:`text-po-faint`,children:`No result details.`}):l(`dl`,{className:`grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-4 gap-y-0.5`,children:e.map(e=>p(`div`,{className:`contents`,children:[l(`dt`,{className:`truncate text-po-dim`,children:e.key}),l(`dd`,{className:`break-words text-po-text`,children:e.value})]},e.key))})}var la=D({tools:[Ti],timelinePresentation:`message`,message:aa}),ua=D({tools:[Ci,wi,Ei],message:aa}),$=(e,t)=>t===void 0?void 0:{...e,...t},da=pe({id:`voice`,packageName:`@agimon-ai/po-voice`,host:{get fills(){return[$({slot:`activity`,id:`voice`},Mt)]},get settingsSections(){return[$({id:`voice`},Kr)]},get start(){return Wr}},workspace:{get settingsSections(){return[$({id:`voice`},qr)]}},session:{get activityGroups(){return[$({name:`voice`},Jr)]},get channels(){return[$({channel:`voice_media_wake`},Yr),$({channel:`voice_ownership`},Xr)]},get fills(){return[$({slot:`approval.voice-hint`,id:`approval-voice-hint`},Zr),$({slot:`activity.voice`,id:`voice`},Qr),$({slot:`composer-actions`,id:`voice`},gi),$({slot:`overlay`,id:`voice`},yi)]},get leaderBindings(){return[$({id:`voice.toggle`},bi)]},get modes(){return[$({name:`voice`},Si)]},get start(){return xi},get toolRenderers(){return[$({tools:[`narrate`]},la),$({tools:[`voice`]},ua)]}}});export{da as webPlugin};
1
+ import{$r as e,At as t,Ba as n,Cn as r,Da as i,Ft as a,Gi as o,Ht as s,In as c,It as l,Ka as u,Ki as d,Kt as f,Lt as p,Ma as m,Mi as h,Mn as g,Mt as _,Na as v,Nn as y,Pa as b,Pi as x,Pn as S,Pr as C,Pt as w,Ra as ee,Ta as T,Un as E,Wa as D,Wi as O,Wn as k,Xi as te,Yi as ne,Zi as re,_n as ie,cn as ae,cr as A,ea as oe,eo as j,gn as se,hn as ce,ii as le,ja as ue,mn as de,na as fe,qa as pe,qi as me,qt as M,vi as he,vn as ge,wa as _e,wi as ve,yn as ye}from"../chunks/po-web-runtime-C0B3uAoC.js";var be=`x-po-client-metadata`,xe=`poClient`,Se=64;function Ce(e){return typeof e==`string`&&/^[A-Za-z0-9_-]{1,64}$/u.test(e)}function we(e){if(typeof e!=`string`)return;let t=e.replaceAll(/[\p{Cc}\p{Cf}]/gu,``).trim(),n=Array.from(t).length;return n>=1&&n<=Se?t:void 0}function Te(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ee(e){if(!Te(e))return{status:`invalid`};if(Number.isSafeInteger(e.version)&&e.version!==1)return{status:`unsupported`};let t=we(e.deviceName);if(e.version!==1||!Ce(e.deviceId)||e.instanceId!==void 0&&!Ce(e.instanceId)||typeof e.clientKind!=`string`||![`web`,`desktop`,`ios`,`android`].includes(e.clientKind)||t===void 0||!Number.isSafeInteger(e.nameUpdatedAt)||typeof e.nameUpdatedAt!=`number`||e.nameUpdatedAt<0)return{status:`invalid`};for(let t of[`browser`,`platform`])if(e[t]!==void 0&&(we(e[t])===void 0||we(e[t])!==e[t]))return{status:`invalid`};return{status:`ok`,metadata:{version:1,deviceId:e.deviceId,...e.instanceId===void 0?{}:{instanceId:e.instanceId},clientKind:e.clientKind,deviceName:t,nameUpdatedAt:e.nameUpdatedAt,...e.browser===void 0?{}:{browser:e.browser},...e.platform===void 0?{}:{platform:e.platform}}}}function De(e){let t=new TextEncoder().encode(JSON.stringify(e));return btoa(String.fromCharCode(...t)).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)}function Oe(e){let t=Ee(e);if(t.status!==`ok`)throw Error(`Invalid Po client metadata`);let n=De(t.metadata);if(n.length>2048)throw Error(`Po client metadata exceeds encoded limit`);return n}function ke(e){try{if(`preface`in e)return!Te(e.preface)||!Object.hasOwn(e.preface,`poClient`)?{status:`absent`}:Object.keys(e.preface).length!==1||De(e.preface.poClient).length>2048?{status:`invalid`}:Ee(e.preface.poClient);let t;if(`query`in e){let n=e.query.getAll(xe);if(n.length>1)return{status:`invalid`};t=n[0]}else t=e.header;if(t==null)return{status:`absent`};if(t.length>2048||!/^[A-Za-z0-9_-]+$/u.test(t))return{status:`invalid`};let n=atob(t.replaceAll(`-`,`+`).replaceAll(`_`,`/`)),r=Uint8Array.from(n,e=>e.charCodeAt(0)),i=new TextDecoder(`utf-8`,{fatal:!0}).decode(r);return btoa(n).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)===t?Ee(JSON.parse(i)):{status:`invalid`}}catch{return{status:`invalid`}}}var N=16e3,Ae=`application/vnd.po.pcm-s16le`,je=`x-po-voice-activity-state`,Me=`x-po-voice-activity-level`,Ne=`x-po-voice-activity-elapsed`,Pe=`x-po-voice-activity-epoch`,Fe=`x-po-voice-activity-speech-ms`,Ie=`x-po-voice-activity-echo-speech-ms`,Le=`voice_media_wake`,P={clientConnect:`/client/connect`,clientDisconnect:`/client/disconnect`,clientEvents:`/client/events`,clientHeartbeat:`/client/heartbeat`,clientAudio:`/client/audio`,clientCaptureStopped:`/client/capture-stopped`,clientPlaybackAudio:`/client/playback-audio`,clientPlaybackResult:`/client/playback-result`,hostCaptureStart:`/host/capture/start`,hostCaptureAudio:`/host/capture/audio`,hostCaptureStop:`/host/capture/stop`,hostCaptureAbort:`/host/capture/abort`,hostPlaybackStart:`/host/playback/start`,hostPlaybackAudio:`/host/playback/audio`,hostPlaybackAudioEnd:`/host/playback/audio-end`,hostPlaybackResult:`/host/playback/result`,hostPlaybackStop:`/host/playback/stop`,hostPlaybackAbort:`/host/playback/abort`},F={audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1};function Re(e){return{...F,audio:{...F.audio,deviceId:{exact:e}}}}function ze(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e;return Object.keys(t).some(e=>![`deviceId`,`eventEpoch`,`sequence`].includes(e))||t.deviceId!==void 0&&!Ce(t.deviceId)||typeof t.eventEpoch!=`string`||t.eventEpoch.length===0||t.eventEpoch.length>200||!Number.isSafeInteger(t.sequence)||t.sequence<0?null:{eventEpoch:t.eventEpoch,sequence:t.sequence,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}}function Be(e,t,n,r,i,a){let o=()=>{let i=e.select(e.store.state,t);return i?.eventEpoch===n&&i.sequence>r?i:void 0},s=o();return s!==void 0||a.aborted?Promise.resolve(s):new Promise(t=>{let n=!1,r,s,c=e=>{n||(n=!0,r!==void 0&&clearTimeout(r),a.removeEventListener(`abort`,l),s?.unsubscribe(),t(e))},l=()=>c();if(s=e.store.subscribe(()=>{let e=o();e!==void 0&&c(e)}),a.addEventListener(`abort`,l,{once:!0}),a.aborted){c();return}r=setTimeout(()=>c(),i);let u=o();u!==void 0&&c(u)})}function Ve(e,t){let n=ke({header:t});return n.status===`ok`&&n.metadata.deviceId===e}var He=`voice_ownership`,Ue=/^[A-Za-z0-9._:-]+$/u;function We(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Ge(e,t){return Object.keys(e).every(e=>t.includes(e))}function Ke(e,t=128){return typeof e==`string`&&e.length>0&&e.length<=t&&Ue.test(e)}function qe(e){return Ke(e,200)||typeof e==`string`&&/^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(e)}function Je(e){let t=We(e);if(t!==void 0&&Ge(t,[`type`,`version`,`deviceId`,`activeSessionId`,`handoff`])&&t.type===`browser-media-session`&&Ce(t.deviceId)&&t.version===5&&(t.activeSessionId===null||qe(t.activeSessionId))){if(t.handoff!==void 0){let e=We(t.handoff);if(e===void 0||!Ge(e,[`id`,`phase`,`sourceSessionId`,`targetSessionId`])||!Ke(e.id)||![`preparing`,`rebinding`,`failed`].includes(e.phase)||!qe(e.sourceSessionId)||e.targetSessionId!==void 0&&!qe(e.targetSessionId)||e.phase===`rebinding`&&e.targetSessionId===void 0)return}return t}}var Ye=4,Xe=Symbol.for(`@agimon-ai/po-voice:web-media-page-state.v4`);function Ze(){return{version:Ye,wakes:ee(void 0),activeSession:m(null),handoff:m(void 0),browserState:m(void 0),realtimeControls:m(void 0),switchPending:m(void 0),runtime:m(void 0)}}function Qe(){let e=globalThis,t=e[Xe];if(t?.version===Ye)return t;let n=Ze();return e[Xe]=n,n}var I=Qe(),$e=I.wakes,L=I.activeSession,et=I.handoff,R=I.browserState,tt=I.runtime,nt=I.switchPending,z=I.realtimeControls,rt={subscribe(e){let t=[R,L,nt].map(t=>t.store.subscribe(e));return()=>{for(let e of t)e.unsubscribe()}},isActive(e){let t=R.store.state,n=t?.sessionId===null&&t.realtime!==void 0&&t.realtime.connection!==`closed`,r=e!==null&&nt.store.state?.sessionId===e;return n||L.store.state!==null||r}},it={subscribe(e){let t=R.store.subscribe(e);return()=>t.unsubscribe()},isActive(){let e=R.store.state;return e?.sessionId===null&&e.realtime!==void 0&&e.realtime.connection!==`closed`}},at={channel:Le,parse:ze,apply(e,t){Ve(t.deviceId,_())&&$e.update(e,e=>e?.eventEpoch===t.eventEpoch&&t.sequence<=e.sequence?e:t)},drop(e){$e.drop(e)}},ot={channel:He,parse(e){return Je(e)??null},apply(e,t){Ve(t.deviceId,_())&&(et.update(()=>t.handoff),L.update(e=>e===t.activeSessionId?e:t.activeSessionId))},drop(e){et.store.state===void 0&&L.update(t=>t===e?null:t)}};function st(e,t,n,r,i){return Be($e,e,t,n,r,i)}var ct=`/manual/transcribe`,lt=`x-po-audio-duration-ms`,ut=3e5,dt={sdpBytes:65536,eventBytes:65536,instructionsCharacters:16384,textCharacters:8192,identifierCharacters:256,pendingRequests:1,retainedRequests:128},ft=new Set([`session.started`,`session.updated`,`input_transcript.added`,`output_transcript.added`,`turn.done`,`delegation.created`]),B={hostStart:`/host/realtime/start`,hostStop:`/host/realtime/stop`,hostPoll:`/host/realtime/poll`,hostSend:`/host/realtime/send`,hostControl:`/host/realtime/control`,clientNegotiate:`/client/realtime/negotiate`,clientEvent:`/client/realtime/event`,clientState:`/client/realtime/state`},pt={status:{method:`GET`,path:`/status`,response:void 0},control:{method:`POST`,path:`/control`,response:void 0},readiness:{method:`GET`,path:`/readiness`,response:void 0},liveStatus:{method:`GET`,path:`/live/status`,response:void 0},liveControl:{method:`POST`,path:`/live/control`,response:void 0},relayBinding:{method:`POST`,path:`/relay-binding`,response:void 0},relay:{method:`POST`,path:`/relay`,query:[`binding`],response:void 0},clientConnect:{method:`POST`,path:P.clientConnect,response:void 0},clientDisconnect:{method:`POST`,path:P.clientDisconnect},clientHeartbeat:{method:`POST`,path:P.clientHeartbeat,response:void 0},clientEvents:{method:`GET`,path:P.clientEvents,query:[`clientId`,`connectionId`,`after`,`wait`],response:void 0},clientAudio:{method:`POST`,path:P.clientAudio,query:[`clientId`,`connectionId`,`captureId`]},clientCaptureStopped:{method:`POST`,path:P.clientCaptureStopped},clientPlaybackAudio:{method:`GET`,path:P.clientPlaybackAudio,query:[`clientId`,`connectionId`,`playbackId`,`wait`]},clientPlaybackResult:{method:`POST`,path:P.clientPlaybackResult},realtimeNegotiate:{method:`POST`,path:B.clientNegotiate,response:void 0},realtimeEvent:{method:`POST`,path:B.clientEvent},realtimeState:{method:`POST`,path:B.clientState},manualTranscribe:{method:`POST`,path:ct,response:void 0}},V=_e(pt,{scopes:[`host`,`workspace`,`session`],basePath:`voice`,transport:(e,n)=>t.fetch(e,n),sessionAddress:j}),H=_e(pt,{scopes:[`host`,`workspace`,`session`],basePath:`voice-media`,transport:(e,n)=>t.fetch(e,n),sessionAddress:j}),mt=/^[⠀-⣿]\s*/u,ht=`voice auto:`,gt=`voice live:`,_t=`voice:`,vt=/\b(\d+:[0-5]\d)\b/u,yt={mode:`off`,phase:`idle`,label:`not listening`,detail:`start autonomous capture from the modes, or dictate one message with the voice tool.`,tone:`idle`,active:!1,microphoneMuted:!1,elapsed:``},bt=[{match:`sending composed prompt`,phase:`sending`,label:`sending draft`,detail:`handing the complete composed prompt to Pi.`,tone:`live`},{match:`composing`,phase:`composing`,label:`composing prompt`,detail:`speech segments are buffered until you say Po send or Po cancel.`,tone:`attention`},{match:`hearing speech`,phase:`hearing`,label:`hearing you`,detail:`speech detected; it will transcribe when you pause.`,tone:`live`},{match:`processing while listening`,phase:`processing`,label:`transcribing`,detail:`still listening while it works out what you said.`,tone:`live`},{match:`narrating`,phase:`narrating`,label:`narrating`,detail:`reading the reply aloud.`,tone:`live`},{match:`microphone muted`,phase:`muted`,label:`microphone muted`,detail:`narration remains active; unmute to start a fresh capture.`,tone:`idle`},{match:`confirmation needed`,phase:`confirming`,label:`needs confirmation`,detail:`it is waiting on an answer before it acts.`,tone:`attention`},{match:`waiting for keyboard input`,phase:`waiting`,label:`waiting for the keyboard`,detail:`something asked for typed input, so capture is paused.`,tone:`attention`},{match:`draining`,phase:`draining`,label:`stopping`,detail:`finishing what it already heard.`,tone:`attention`},{match:`starting`,phase:`starting`,label:`starting`,detail:`preparing autonomous microphone capture.`,tone:`live`},{match:`listening`,phase:`listening`,label:`listening`,detail:``,tone:`live`}];function xt(e){let t=(e??``).replace(mt,``).trim();if(t===``)return yt;if(t.startsWith(ht)){let e=t.slice(11).trim(),n=e.includes(`microphone muted`),r=bt.find(t=>e.includes(t.match));return r?{mode:`auto`,phase:r.phase,label:r.label,detail:r.detail,tone:r.tone,active:r.phase!==`muted`,microphoneMuted:n,elapsed:``}:{...yt,mode:`auto`,label:e||`listening`,detail:``,tone:`live`,active:!0,microphoneMuted:n}}if(t.startsWith(gt))return{mode:`live`,phase:`listening`,label:`talking`,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``};if(t.startsWith(_t)){let e=t.slice(6).trim(),n=e.startsWith(`recording`);return{mode:`manual`,phase:n?`recording`:`transcribing`,label:n?`recording`:`transcribing`,detail:n?`the microphone is open; it sends when you stop.`:`turning what you said into text.`,tone:n?`attention`:`live`,active:!0,microphoneMuted:!1,elapsed:n?vt.exec(e)?.[1]??``:``}}return{mode:`auto`,phase:`listening`,label:t,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``}}function St({state:t,takeOver:n,retry:r,mute:i,end:a,pending:o,error:s}){let c=t.kind===`deviceLive`,u=t.kind===`standby`,d=t.ownerName??`another device`;return p(`section`,{"aria-label":`Voice`,className:`flex flex-col gap-3`,children:[l(`h3`,{className:`text-lg font-semibold text-po-hi`,children:`Voice`}),p(`div`,{className:`flex items-center gap-2`,children:[l(oe,{tone:c?`cyan`:u?`muted`:`magenta`}),l(`span`,{className:`text-base font-semibold text-po-hi`,children:u?`Voice is on standby`:c?`Live on this device`:`Voice is active on ${d}`})]}),l(`p`,{className:`text-sm leading-relaxed text-po-dim`,children:u?`Another window on this device is using voice. This window is not listening.`:c?`${t.deviceName??`This device`} · Microphone live. Other devices can run their own Live conversations separately.`:t.kind===`stale`?`Voice moved since you last checked. Take over from ${d} whenever you are ready.`:`This device is not listening. You can move this session’s voice here whenever you are ready.`}),t.kind===`conflict`||t.kind===`stale`?l(`div`,{children:l(e,{variant:`secondary`,disabled:o||!n,onClick:n,children:`Take over`})}):c?p(`div`,{className:`flex gap-2`,children:[l(e,{variant:`subtle`,disabled:o||!i,onClick:i,children:`Mute`}),l(e,{variant:`subtle`,disabled:o||!a,onClick:a,children:`End Live on this device`})]}):null,c?l(`p`,{className:`text-sm text-po-dim`,children:`Each device’s Live conversation is billed separately.`}):null,s?l(`p`,{role:`alert`,className:`text-sm text-po-red`,children:s}):null,s&&r?l(`div`,{children:l(e,{variant:`subtle`,disabled:o,onClick:r,children:`Try again`})}):null]})}var Ct={idle:`muted`,live:`cyan`,attention:`yellow`},wt={idle:`text-po-dim`,live:`text-po-cyan`,attention:`text-po-yellow`};function Tt({tone:e}){return l(`span`,{"aria-hidden":!0,className:`flex h-3 items-end gap-[2px]`,children:[3,7,5,9,4].map((t,n)=>l(`span`,{className:`w-[2px] animate-pulse rounded-xs ${e===`attention`?`bg-po-yellow`:`bg-po-cyan`}`,style:{height:`${String(t)}px`,animationDelay:`${String(n*120)}ms`}},n))})}function U({label:t,onClick:n,pending:r,...i}){return n===void 0?null:l(e,{variant:`subtle`,size:`xs`,disabled:r,onClick:n,...i,children:t})}function Et(e,t){return e===void 0?``:t?`output interrupted locally and will stay silent until this realtime session ends.`:e.error?e.error:e.speaking?`assistant speaking`:e.muted?`microphone muted`:e.listening?`microphone live`:`establishing secure media`}function Dt(e){switch(e.kind){case`switching`:return{phase:`switching`,tone:`live`,pulse:!0,label:`switching to ${e.mode===`live`?`live conversation`:`daily work`}`,detail:e.mode===`live`?`daily work stopped listening. Live opens the microphone once it connects.`:`live has ended. Daily work starts listening in a moment.`,meter:!1};case`conflict`:return{phase:`conflict`,tone:`attention`,pulse:!1,label:`microphone unavailable`,detail:`another Po window (the desktop app or a browser tab) is using the microphone. Close that window to use it here.`,meter:!1};case`daily`:return{phase:e.view.phase,tone:e.view.tone,pulse:e.view.active,label:e.view.label,detail:e.view.detail||(e.view.phase===`listening`&&!e.signInHint?`speak whenever you are ready`:``),meter:e.view.active};case`live`:{let t=e.realtime?.connection??`connected`,n=t===`connected`;return{phase:`realtime-${t}`,tone:n?`live`:`attention`,pulse:n,label:n?`talking`:`connecting live conversation`,detail:Et(e.realtime,e.interrupted),meter:n&&e.realtime!==void 0&&!e.realtime.muted}}case`live-failed`:return{phase:`realtime-failed`,tone:`attention`,pulse:!1,label:`live could not connect`,detail:e.error,meter:!1};case`live-elsewhere`:return{phase:`live-elsewhere`,tone:`idle`,pulse:!1,label:`live is talking in another session`,detail:``,meter:!1};case`daily-elsewhere`:return{phase:`daily-elsewhere`,tone:`idle`,pulse:!1,label:`daily work is listening in another session`,detail:``,meter:!1};case`manual`:case`idle`:return{phase:e.view.phase,tone:e.view.tone,pulse:e.view.active,label:e.view.label,detail:e.view.detail,meter:e.view.active,elapsed:e.view.elapsed}}}function Ot({state:t,picker:n,actions:r,pending:i,error:a,ownership:o,ownershipActions:s}){if(o)return l(St,{state:o,takeOver:s?.takeOver,retry:s?.retry,mute:r.mute,end:r.end,pending:i,error:a});let c=Dt(t),u=t.kind===`daily`&&t.view.microphoneMuted,d=t.kind===`live`&&t.realtime?.muted===!0,f=u||d?`unmute`:`mute`,m=t.kind===`live-failed`,h=t.kind===`daily`&&t.signInHint;return p(`div`,{"data-testid":`voice-activity`,"data-voice-phase":c.phase,className:`flex flex-col gap-2 px-1`,children:[n===void 0?null:p(E,{"aria-label":`Voice for this session`,value:n.value,disabled:n.disabled||i,onValueChange:e=>n.onPick(e),className:`grid grid-cols-2 gap-1.5`,children:[l(k,{value:`live`,"data-testid":`voice-pick-live`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Live`}),l(k,{value:`legacy`,"data-testid":`voice-pick-legacy`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Daily work`})]}),p(`span`,{className:`flex min-w-0 items-center gap-2`,children:[l(oe,{tone:Ct[c.tone],pulse:c.pulse}),l(`span`,{"data-testid":`voice-label`,className:`flex-1 truncate text-base font-semibold ${wt[c.tone]}`,children:c.label}),c.elapsed?l(`span`,{"data-testid":`voice-elapsed`,className:`shrink-0 text-sm tabular-nums text-po-yellow`,children:c.elapsed}):null,c.meter?l(Tt,{tone:c.tone}):null]}),t.kind===`daily`||t.kind===`live`?p(`span`,{className:`flex flex-wrap gap-1.5`,children:[l(U,{label:f,onClick:r.mute,pending:i,"aria-pressed":u||d,...t.kind===`daily`?{"data-testid":`voice-autonomous-microphone-toggle`,"aria-label":`${f} autonomous voice microphone`,title:`${f} autonomous voice microphone`}:{}}),l(U,{label:`interrupt`,onClick:t.kind===`live`?r.interrupt:void 0,pending:i,title:`Interrupt local output. Output stays silent until this realtime session ends.`}),l(U,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,c.detail&&!h?l(`span`,{"data-testid":`voice-detail`,role:m?`alert`:void 0,className:`text-sm leading-relaxed text-po-dim`,children:m&&r.useDailyWork!==void 0?`${c.detail} You can keep talking with daily work.`:c.detail}):null,h?p(`span`,{className:`flex flex-col items-start gap-2`,children:[l(`span`,{"data-testid":`voice-sign-in-hint`,className:`text-sm leading-relaxed text-po-dim`,children:`live needs your ChatGPT for Po features sign-in. Daily work keeps listening meanwhile.`}),r.signIn===void 0?null:l(e,{variant:`secondary`,size:`xs`,"data-testid":`voice-sign-in`,onClick:r.signIn,children:`sign in`})]}):null,m?p(`span`,{className:`flex flex-wrap gap-1.5`,children:[l(U,{label:`use daily work`,onClick:r.useDailyWork,pending:i,"data-testid":`voice-use-daily`}),l(U,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,t.kind===`live-elsewhere`||t.kind===`daily-elsewhere`?l(`span`,{className:`flex`,children:l(U,{label:t.kind===`live-elsewhere`?`move Live here`:`move daily work here`,onClick:t.kind===`live-elsewhere`?r.routeLiveHere:r.moveDailyWorkHere,pending:i,"data-testid":t.kind===`live-elsewhere`?`voice-global-live-transfer`:`voice-daily-move`})}):null,a===null?null:l(`span`,{role:`alert`,className:`text-sm leading-relaxed text-po-yellow`,children:a})]})}function kt(e){return e instanceof Error?e.message:String(e)}function At({sessionId:e,statuses:t,openSettings:n,registeredModes:r}){let i=xt(t[`po-voice`]),a=w(R.store),o=w(z.store),c=w(L.store),u=w(nt.store),[d,f]=M(!1),[p,m]=M(null),[h,g]=M(!1),[_,v]=M(),y=r?.includes(`voice-auto`)===!0;s(()=>{if(e===null||!y)return;let t=!1;return V.session(e).status().then(n=>{!t&&n.ok&&v({sessionId:e,realtime:n.data.media.realtime})}).catch(()=>{t||v({sessionId:e,realtime:!1})}),()=>{t=!0}},[y,e]);let b=e===null||(_?.sessionId===e?_.realtime:a?.realtime!==void 0||i.mode===`live`||u?.sessionId===e&&u?.mode===`live`),x=e!==null&&a?.sessionId===e?a.realtime:void 0,S=a?.sessionId===null?a.realtime:void 0,C=x??S,ee=C!==void 0&&C.connection!==`closed`,T=o?.sessionId===null||o?.sessionId===e?o:void 0,E=e!==null&&u?.sessionId===e?{kind:`switching`,mode:u.mode}:e!==null&&a?.sessionId===e&&a.phase===`conflict`&&i.mode!==`off`?{kind:`conflict`}:i.mode===`auto`?{kind:`daily`,view:i,signInHint:h}:C?.connection===`failed`&&i.mode!==`manual`?{kind:`live-failed`,error:C.error??`the live provider did not answer.`}:e!==null&&i.mode!==`live`&&x===void 0&&S?.connection===`connected`?{kind:`live-elsewhere`}:i.mode===`live`||ee?{kind:`live`,...C===void 0?{}:{realtime:C},interrupted:a?.realtimeOutputInterrupted===!0}:c!==null&&c!==e&&i.mode===`off`?{kind:`daily-elsewhere`}:i.mode===`manual`?{kind:`manual`,view:i}:{kind:`idle`,view:i},D=async e=>{if(!d){f(!0),m(null);try{await e()}catch(e){m(kt(e))}finally{f(!1)}}},O=async(t,n,r,i)=>{if(e===null)throw Error(`Voice controls need a session.`);if((t===`activate`||t===`switch`)&&n!==`live`){let a=tt.store.state;if(!a)throw Error(`Voice media is not ready in this browser.`);try{r=await a.prepareSessionActivation(e,i)}catch(r){throw R.update(r=>{if(r?.sessionId!==e||!r.ownershipConflict)return r;let i=r.ownershipConflict.owner.generation;return{...r,actions:{takeOver:()=>{D(()=>O(t,n,void 0,i))},retry:()=>{D(()=>O(t,n))}}}}),r}}if(t===`switch`&&n===`live`&&!r){let e=tt.store.state;if(!e)throw Error(`Voice media is not ready in this browser.`);r=await e.prepareLiveActivation(i)}let a=await V.session(e).control({body:{action:t,...n?{mode:n}:{},...r?{browser:r}:{},...i===void 0?{}:{takeoverGeneration:i}}});if(a.ok&&a.data.ownershipConflict){let r=a.data.ownershipConflict,o=i!==void 0;R.update(()=>({sessionId:e,phase:`conflict`,ownershipConflict:r,ownership:{kind:o?`stale`:`conflict`,ownerName:r.owner.deviceName},actions:{takeOver:()=>{D(()=>O(t,n,void 0,r.owner.generation))},retry:()=>{D(()=>O(t,n))}}}))}else if(!a.ok)throw Error(a.error||`Voice control request failed.`)},k=async(t,n)=>{if(e===null)return;g(!1);let r={sessionId:e,mode:t};nt.update(()=>r);try{await n()}finally{nt.update(e=>e===r?void 0:e)}},te=(e,t)=>D(()=>k(e,t)),ne=()=>D(async()=>{let e=await V.host.liveStatus();if(e.ok&&e.data.signedIn===!1){g(!0);return}if(!e.ok)throw Error(e.error);if(e.data.state!==`disabled`)return;let t=tt.store.state;if(!t)throw Error(`Voice media is not ready in this browser.`);let n=await t.prepareLiveActivation();await k(`live`,()=>O(`switch`,`live`,n))}),re=()=>te(`legacy`,async()=>{b&&await ie(`end`),await O(`activate`,`legacy`)}),ie=async e=>{let t=await V.host.liveControl({body:{action:e}});if(!t.ok)throw Error(t.error||`Live control request failed.`)},ae=()=>T?T.end():void D(()=>ie(`end`)),A={},oe,j=(t,n,r=!1)=>{e!==null&&b&&(oe={value:n,disabled:r,onPick:t})};switch(E.kind){case`switching`:j(()=>void 0,E.mode,!0);break;case`daily`:if(e===null)break;j(e=>void(e===`live`?ne():void 0),`legacy`),i.phase!==`starting`&&i.phase!==`draining`&&(A.mute=()=>void D(()=>O(i.microphoneMuted?`unmute`:`mute`))),A.end=()=>void D(()=>O(`deactivate`)),n&&(A.signIn=()=>n(`providers`));break;case`live`:{let e=E.realtime?.muted===!0;j(e=>void(e===`legacy`?re():void 0),`live`),A.mute=()=>T?T.mute(!e):void D(()=>ie(e?`unmute`:`mute`)),A.interrupt=()=>T?T.interrupt():void D(()=>ie(`interrupt`)),A.end=ae;break}case`live-failed`:j(e=>void(e===`legacy`?re():void 0),`live`),e!==null&&(A.useDailyWork=()=>void re()),A.end=ae;break;case`live-elsewhere`:j(()=>void 0,`live`,!0),e!==null&&(A.routeLiveHere=()=>void D(async()=>{let t=await V.host.liveControl({body:{action:`transfer`,sessionId:e}});if(!t.ok)throw Error(t.error||`Moving Live here failed.`)}));break;case`daily-elsewhere`:j(()=>void 0,`legacy`,!0),e!==null&&(A.moveDailyWorkHere=()=>void D(()=>O(`activate`,`legacy`)))}let se=a?.sessionId===e||a?.sessionId===null?a:void 0;return l(Ot,{state:E,picker:oe,actions:A,pending:d,error:p,ownership:se?.ownership,ownershipActions:se?.actions})}function jt(e){let t=w(R.store);return e.sessionId!==null||t?.sessionId!==null||t.realtime?.connection===`closed`||t.realtime===void 0?null:l(At,{...e})}var Mt=ue({slot:`activity`,id:`voice-global-live`,component:jt}),Nt=1e4,Pt=15e3,Ft=15e3;function It(e){return new TextEncoder().encode(e).byteLength}function Lt(e){if(typeof e!=`object`||!e)return;let t=e.type;return typeof t==`string`?t:void 0}function W(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}var Rt=class{options;microphoneConstraints;browser;output;state={connection:`closed`,listening:!1,speaking:!1,muted:!1};generation=0;started=!1;stream;peer;channel;audio;abortController;suppressOutput=!1;announcements=new Map;announcementFlushScheduled=!1;constructor(e,t=async()=>F,n=window,r){this.options=e,this.microphoneConstraints=t,this.browser=n,this.output=r,this.state.muted=e.muted===!0,r&&(r.onPlaybackState=e=>{this.state.connection!==`closed`&&this.state.connection!==`failed`&&(this.publish({speaking:e&&!this.suppressOutput}),e||this.scheduleAnnouncementFlush())})}async start(){if(this.started)throw Error(`Realtime browser session has already started.`);this.started=!0;let e=++this.generation,t=new AbortController;this.abortController=t,this.publish({connection:`connecting`,error:void 0});try{if(typeof this.browser.RTCPeerConnection!=`function`||this.browser.navigator.mediaDevices?.getUserMedia===void 0)throw Error(`Browser realtime media is unavailable.`);let n=this.microphoneConstraints().then(e=>this.browser.navigator.mediaDevices.getUserMedia(e));n.then(t=>{if(!this.isCurrent(e))for(let e of t.getTracks())e.stop()},()=>void 0);let r=await this.abortable(n,t.signal);if(!this.isCurrent(e)){for(let e of r.getTracks())e.stop();throw Error(`Realtime browser session was closed.`)}this.stream=r;for(let t of r.getTracks())t.kind===`audio`&&(t.enabled=!this.state.muted),t.onended=()=>this.fail(e,`Microphone permission or input was lost.`);let i=new this.browser.RTCPeerConnection;this.peer=i,i.onconnectionstatechange=()=>{this.isCurrent(e)&&(i.connectionState===`failed`||i.connectionState===`disconnected`?this.fail(e,`Realtime connection ${i.connectionState}.`):i.connectionState===`closed`&&this.state.connection!==`closed`&&this.fail(e,`Realtime connection closed unexpectedly.`))},i.ontrack=t=>this.attachRemoteAudio(e,t);let a=i.createDataChannel(`oai-events`);this.channel=a,a.onmessage=t=>this.receive(e,t.data),a.onerror=()=>this.fail(e,`Realtime event channel failed.`),a.onclose=()=>{this.isCurrent(e)&&this.fail(e,`Realtime event channel closed unexpectedly.`)};for(let e of r.getTracks())i.addTrack(e,r);let o=await i.createOffer();this.assertSdp(o.sdp),await i.setLocalDescription(o),await this.waitForIce(i,e,t.signal);let s=i.localDescription?.sdp;this.assertSdp(s);let c=await this.bounded(this.options.negotiate(s,t.signal),Ft,`Realtime negotiation timed out.`,t.signal);if(this.assertSdp(c),!this.isCurrent(e)||(await i.setRemoteDescription({type:`answer`,sdp:c}),await this.waitForConnection(i,a,e,t.signal),!this.isCurrent(e)))throw Error(`Realtime browser session was closed.`);this.publish({connection:`connected`,listening:!this.state.muted})}catch(t){throw this.isCurrent(e)&&this.fail(e,W(t)),t}}send(e){if(this.validateEvent(e),this.channel?.readyState!==`open`||this.state.connection!==`connected`)throw Error(`Realtime event channel is not open.`);let t=JSON.parse(e);if(t.type===`po.announce`){if(typeof t.key!=`string`||t.key.length===0||t.text!==void 0&&typeof t.text!=`string`)throw Error(`Realtime announcement requires a key and optional text.`);t.text===void 0?this.announcements.delete(t.key):this.announcements.set(t.key,t.text),this.scheduleAnnouncementFlush()}else this.channel.send(e)}mute(e){for(let t of this.stream?.getAudioTracks()??[])t.enabled=!e;this.publish({muted:e,listening:this.state.connection===`connected`&&!e})}interruptSpeech(){this.suppressOutput=!0,this.audio!==void 0&&(this.audio.muted=!0),this.output?.suppress(!0),this.publish({speaking:!1})}close(){this.state.connection===`closed`&&this.generation>0||(this.started=!0,this.generation+=1,this.cleanup(),this.publish({connection:`closed`,listening:!1,speaking:!1,error:void 0}))}receive(e,t){if(!this.isCurrent(e))return;if(typeof t!=`string`||It(t)>dt.eventBytes){this.fail(e,`Realtime provider sent an invalid or oversized event.`);return}let n;try{n=JSON.parse(t)}catch{this.fail(e,`Realtime provider sent malformed JSON.`);return}let r=Lt(n);if(r===void 0)this.fail(e,`Realtime provider sent an event without a type.`);else if(r===`error`)this.fail(e,`Realtime provider reported an error.`);else if(r===`input_transcript.added`&&this.suppressOutput&&(this.suppressOutput=!1,this.audio!==void 0&&(this.audio.muted=!1),this.output?.suppress(!1)),ft.has(r))try{this.options.onEvent(t)}catch(t){this.fail(e,`Realtime event consumer failed: ${W(t)}`)}}attachRemoteAudio(e,t){if(!this.isCurrent(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??new this.browser.MediaStream([t.track]);if(this.output){this.output.suppress(this.suppressOutput);try{Promise.resolve(this.output.attach(n,t.track)).catch(t=>this.fail(e,`Remote audio playback failed: ${W(t)}`))}catch(t){this.fail(e,`Remote audio playback failed: ${W(t)}`)}return}let r=this.browser.document.createElement(`audio`);r.autoplay=!0,r.muted=this.suppressOutput,r.srcObject=n,r.onplaying=()=>{this.isCurrent(e)&&this.audio===r&&!r.muted&&this.publish({speaking:!0})};let i=()=>{this.isCurrent(e)&&this.audio===r&&(this.publish({speaking:!1}),this.scheduleAnnouncementFlush())};r.onpause=i,r.onended=i,r.onwaiting=i,this.detachAudio(),this.audio=r,r.play().catch(t=>this.fail(e,`Remote audio playback failed: ${W(t)}`))}scheduleAnnouncementFlush(){if(this.announcementFlushScheduled||this.announcements.size===0)return;this.announcementFlushScheduled=!0;let e=this.generation;queueMicrotask(()=>{if(this.announcementFlushScheduled=!1,!this.isCurrent(e)||this.state.connection!==`connected`||this.channel?.readyState!==`open`||this.suppressOutput)return;let t=e=>JSON.stringify({type:`session.context.append`,channel:`speakable`,content:[{type:`input_text`,text:`Share these updates only at a conversational pause. Stop and listen when the user speaks.\n\n${e}`}]}),n=[],r=``;for(let e of this.announcements.values()){let i=Array.from(e);for(let e=0;e<i.length;e+=4096){let a=i.slice(e,e+4096).join(``),o=r?`${r}\n\n${a}`:a;It(t(o))>dt.eventBytes?(n.push(t(r)),r=a):r=o}}r&&n.push(t(r)),this.announcements.clear();try{for(let e of n)this.channel.send(e)}catch(t){this.fail(e,`Realtime announcement failed: ${W(t)}`)}})}validateEvent(e){if(It(e)>dt.eventBytes)throw Error(`Realtime event exceeds the maximum size.`);let t;try{t=JSON.parse(e)}catch{throw Error(`Realtime event must be valid JSON.`)}if(Lt(t)===void 0)throw Error(`Realtime event must contain a type.`)}assertSdp(e){if(typeof e!=`string`||e.length===0)throw Error(`Realtime SDP is missing.`);if(It(e)>dt.sdpBytes)throw Error(`Realtime SDP exceeds the maximum size.`)}async waitForIce(e,t,n){if(e.iceGatheringState===`complete`)return;let r=()=>{this.isCurrent(t)&&e.iceGatheringState===`complete`&&i?.()},i;try{await this.bounded(new Promise(t=>{i=t,e.addEventListener(`icegatheringstatechange`,r),r()}),Nt,`Realtime ICE gathering timed out.`,n)}finally{e.removeEventListener(`icegatheringstatechange`,r)}}async waitForConnection(e,t,n,r){let i=()=>e.connectionState===`connected`&&t.readyState===`open`;if(i())return;let a=()=>{this.isCurrent(n)&&(e.connectionState===`failed`||e.connectionState===`disconnected`?s?.(Error(`Realtime connection ${e.connectionState}.`)):i()&&o?.())},o,s;try{await this.bounded(new Promise((n,r)=>{o=n,s=r,e.addEventListener(`connectionstatechange`,a),t.addEventListener(`open`,a),t.addEventListener(`close`,a),a()}),Pt,`Realtime connection timed out.`,r)}finally{e.removeEventListener(`connectionstatechange`,a),t.removeEventListener(`open`,a),t.removeEventListener(`close`,a)}}abortable(e,t){return new Promise((n,r)=>{let i=!1,a=e=>{i||(i=!0,t.removeEventListener(`abort`,o),e())},o=()=>a(()=>r(Error(`Realtime browser session was closed.`)));t.addEventListener(`abort`,o,{once:!0}),t.aborted&&o(),e.then(e=>a(()=>n(e)),e=>a(()=>r(e)))})}bounded(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(l),r.removeEventListener(`abort`,c),e())},c=()=>s(()=>a(Error(`Realtime browser session was closed.`))),l=setTimeout(()=>s(()=>a(Error(n))),t);r.addEventListener(`abort`,c,{once:!0}),r.aborted&&c(),e.then(e=>s(()=>i(e)),e=>s(()=>a(e)))})}fail(e,t){this.isCurrent(e)&&(this.generation+=1,this.cleanup(),this.publish({connection:`failed`,listening:!1,speaking:!1,error:t}))}cleanup(){this.announcements.clear(),this.abortController?.abort(),this.abortController=void 0,this.channel!==void 0&&(this.channel.onmessage=null,this.channel.onerror=null,this.channel.onclose=null,this.channel.close()),this.peer!==void 0&&(this.peer.ontrack=null,this.peer.onconnectionstatechange=null,this.peer.close());for(let e of this.stream?.getTracks()??[])e.onended=null,e.stop();this.detachAudio(),this.output&&(this.output.onPlaybackState=null,this.output.dispose()),this.channel=void 0,this.peer=void 0,this.stream=void 0,this.suppressOutput=!1}detachAudio(){this.audio!==void 0&&(this.audio.onplaying=null,this.audio.onpause=null,this.audio.onended=null,this.audio.onwaiting=null,this.audio.pause(),this.audio.srcObject=null,this.audio=void 0)}publish(e){this.state={...this.state,...e};try{this.options.onState({...this.state})}catch(e){queueMicrotask(()=>{throw e})}}isCurrent(e){return this.generation===e}},zt=600,Bt=N*120/1e3,Vt=-120,Ht=32768,Ut=2,Wt=N*1*Ut;function Gt(e,t,n){return Math.min(n,Math.max(t,e))}function Kt(e){return Math.round(e*10)/10}function qt(e){if(e.byteLength===0||e.byteLength%Ut!==0)throw Error(`PCM activity input must contain complete 16-bit samples.`);let t=0;for(let n=0;n<e.byteLength;n+=Ut){let r=e[n]|e[n+1]<<8,i=(r>=32768?r-65536:r)/Ht;t+=i*i}let n=Math.sqrt(t/(e.byteLength/Ut));return n===0?Vt:20*Math.log10(n)}var Jt=class{endpointSilenceMs;elapsedBytes=0;activityEpoch=0;consecutiveSpeechSamples=0;consecutiveEchoSpeechSamples=0;classifiedSpeechSamples=0;echoDiscriminatedSpeechSamples=0;trailingSilenceSamples=0;speechStarted=!1;endpointReached=!1;previousEchoDiscriminated=!1;constructor(e=zt){if(this.endpointSilenceMs=e,!Number.isSafeInteger(e)||e<250)throw Error(`Client endpoint silence must be an integer of at least 250 ms.`)}push(e,t=[],n){let r=qt(e);this.elapsedBytes+=e.byteLength;let i=n?.echoReferenceActive===!0&&n.echoDiscriminated&&this.previousEchoDiscriminated;for(let e of t){if(!Number.isSafeInteger(e.sampleCount)||e.sampleCount<=0)throw Error(`Speech-presence windows must contain a positive integer sample count.`);if(this.endpointReached){if(!e.speech){this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0;continue}if(this.consecutiveSpeechSamples+=e.sampleCount,i&&(this.consecutiveEchoSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples<Bt)continue;this.activityEpoch+=1,this.classifiedSpeechSamples=this.consecutiveSpeechSamples,this.echoDiscriminatedSpeechSamples=this.consecutiveEchoSpeechSamples,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.trailingSilenceSamples=0,this.speechStarted=!0,this.endpointReached=!1;continue}e.speech?(this.classifiedSpeechSamples+=e.sampleCount,i&&(this.echoDiscriminatedSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples+=e.sampleCount,i&&(this.consecutiveEchoSpeechSamples+=e.sampleCount),this.consecutiveSpeechSamples>=Bt&&(this.speechStarted=!0,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.trailingSilenceSamples=0)):(this.speechStarted&&(this.trailingSilenceSamples+=this.consecutiveSpeechSamples+e.sampleCount),this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0);let t=this.trailingSilenceSamples/N*1e3;this.speechStarted&&t>=this.endpointSilenceMs&&(this.endpointReached=!0)}return this.previousEchoDiscriminated=n?.echoReferenceActive===!0&&n.echoDiscriminated,{state:this.endpointReached?`endpoint`:this.speechStarted?`speech`:`listening`,levelDbfs:Kt(Gt(r,Vt,0)),elapsedMs:Math.round(this.elapsedBytes/Wt*1e3),epoch:this.activityEpoch,classifiedSpeechMs:Math.round(this.classifiedSpeechSamples/N*1e3),...n?.echoReferenceActive===!0?{echoDiscriminatedSpeechMs:Math.round(this.echoDiscriminatedSpeechSamples/N*1e3)}:{}}}resetActivity(){this.activityEpoch+=1,this.consecutiveSpeechSamples=0,this.consecutiveEchoSpeechSamples=0,this.classifiedSpeechSamples=0,this.echoDiscriminatedSpeechSamples=0,this.trailingSilenceSamples=0,this.speechStarted=!1,this.endpointReached=!1,this.previousEchoDiscriminated=!1}},Yt=2e3,Xt=16e3,Zt=200,Qt=128,$t=2097152,en=409;function tn(e){return e instanceof Error&&`status`in e&&e.status===en}function nn(e){if(!(e instanceof Error)||!(`conflict`in e))return!1;let t=e.conflict;return typeof t==`object`&&!!t&&`code`in t&&t.code===`VOICE_OWNERSHIP_CONFLICT`}function rn(e,t){return{playbackId:e,outcome:`failed`,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}function an(e){return{...e}}function on(e,t){return e.capture===t.capture&&e.playback===t.playback&&e.captureActivity===t.captureActivity&&e.autonomousOrchestration===t.autonomousOrchestration&&e.playbackDucking===t.playbackDucking&&e.realtime===t.realtime}function sn(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0})})}var cn=class{clientId;connectionId;transport;device;onConnectionState;onRealtimeState;createRealtimeSession;onOpenSession;abortController=new AbortController;capture;captureId;advertisedCapabilities;captureGeneration=0;speechDetector;activityLifecycle;playback;playbackAudioController;audioUploads=Promise.resolve();audioUploadError;activeConnectionId;connectionAttempt=0;ownershipError;connectionWaiters=new Set;failAttempt;runOperation;realtime;realtimeActivationId;realtimeGeneration=0;realtimePosts=Promise.resolve();pendingRealtimePosts=0;listeningWaiters=new Set;captureEndWaiters=new Set;constructor(e,t,n,r,i=()=>void 0,a=()=>void 0,o,s){this.clientId=e,this.connectionId=t,this.transport=n,this.device=r,this.onConnectionState=i,this.onRealtimeState=a,this.createRealtimeSession=o,this.onOpenSession=s}start(){this.onConnectionState(`connecting`),this.runOperation??=this.run()}waitForConnection(){return this.activeConnectionId===void 0?this.ownershipError?Promise.reject(this.ownershipError):this.abortController.signal.aborted?Promise.reject(Error(`Voice media client is closed.`)):new Promise((e,t)=>{let n=i=>{clearTimeout(r),this.connectionWaiters.delete(n),i?t(i):this.activeConnectionId===void 0?t(Error(`Voice media connection is unavailable.`)):e({clientId:this.clientId,connectionId:this.activeConnectionId})},r=setTimeout(()=>n(Error(`The requesting browser did not connect to Voice.`)),1e4);this.connectionWaiters.add(n)}):Promise.resolve({clientId:this.clientId,connectionId:this.activeConnectionId})}get listening(){return this.capture!==void 0}waitForListening(){return this.listening?Promise.resolve(!0):this.abortController.signal.aborted?Promise.resolve(!1):new Promise(e=>this.listeningWaiters.add(e))}waitForCaptureEnd(){return this.captureId===void 0||this.abortController.signal.aborted?Promise.resolve():new Promise(e=>this.captureEndWaiters.add(e))}async stop(e=!0){this.closeRealtime(),this.abortController.abort();for(let e of this.connectionWaiters)e(Error(`Voice media client is closed.`));await this.runOperation?.catch(()=>void 0),await this.releaseMedia(e);let t=this.activeConnectionId;t!==void 0&&await this.transport.disconnect(this.clientId,t).catch(()=>void 0),this.activeConnectionId=void 0,this.advertisedCapabilities=void 0,this.resolveListening(!1),this.resolveCaptureEnd(),this.onConnectionState(`disconnected`)}async run(){let e=this.abortController.signal,t=Yt;for(;!e.aborted;){let n=this.nextConnectionId(),r=new AbortController,i=()=>r.abort();e.addEventListener(`abort`,i,{once:!0});let a,o=new Promise((e,t)=>{a=t});this.failAttempt=a;try{let i=an(this.device.capabilities),a=await this.transport.connect(this.clientId,n,i);if(e.aborted){await this.transport.disconnect(this.clientId,n).catch(()=>void 0);return}this.activeConnectionId=n,this.advertisedCapabilities=i,t=Yt,this.onConnectionState(`connected`);for(let e of this.connectionWaiters)e();this.prepareCapabilities(n,i,r.signal);let s=a.cursor;for(;!e.aborted;){let e=await Promise.race([this.transport.nextEvent(this.clientId,n,s,r.signal),o]);e!==void 0&&(s=e.sequence,await this.handle(e,n))}}catch(i){for(let e of this.connectionWaiters)e(i instanceof Error?i:Error(String(i)));if(e.aborted)return;if(tn(i)&&(this.activeConnectionId!==n||nn(i))&&this.onConnectionState(`conflict`,i),r.abort(),this.closeRealtime(tn(i)),await this.releaseMedia(),this.activeConnectionId===n&&(await this.transport.disconnect(this.clientId,n).catch(()=>void 0),this.activeConnectionId=void 0,this.advertisedCapabilities=void 0),tn(i)&&nn(i)){this.ownershipError=i;return}await sn(t,e),t=Math.min(t*2,Xt)}finally{e.removeEventListener(`abort`,i),this.failAttempt===a&&(this.failAttempt=void 0)}}}prepareCapabilities(e,t,n){(async()=>{try{if(await this.device.prepare?.(),n.aborted||this.abortController.signal.aborted||this.activeConnectionId!==e)return;let r=an(this.device.capabilities);if(on(t,r)||!this.transport.refreshCapabilities)return;await this.transport.refreshCapabilities(this.clientId,e,r),this.activeConnectionId===e&&(this.advertisedCapabilities=r)}catch{}})()}async handle(e,t){switch(e.type){case`realtime-start`:this.startRealtime(e.activationId,t,e.muted===!0);return;case`realtime-stop`:this.realtimeActivationId===e.activationId&&this.closeRealtime();return;case`realtime-control`:if(this.realtimeActivationId!==e.activationId)return;e.action===`mute`?this.realtime?.mute(!0):e.action===`unmute`?this.realtime?.mute(!1):this.realtime?.interruptSpeech();return;case`realtime-send`:if(this.realtimeActivationId!==e.activationId)return;for(let t of e.messages)this.realtime?.send(t);return;case`open-session`:this.realtimeActivationId===e.activationId&&this.onOpenSession?.(e.sessionId);return;case`capture-start`:this.closeRealtime(),await this.startCapture(e,t);return;case`capture-stop`:this.captureId===e.captureId&&await this.finishCapture(e.captureId,t,!0);return;case`capture-abort`:this.captureId===e.captureId&&await this.finishCapture(e.captureId,t,!1);return;case`playback-start`:this.closeRealtime(),await this.startPlayback(e,t);return;case`playback-stop`:this.playbackAudioController?.abort(),this.playback?.stop(`stopped`);return;case`playback-abort`:this.playbackAudioController?.abort(),this.playback?.stop(`aborted`);return}}muteRealtime(e){this.realtime?.mute(e)}interruptRealtime(){this.realtime?.interruptSpeech()}endRealtime(){this.closeRealtime()}startRealtime(e,t,n){this.closeRealtime();let r=++this.realtimeGeneration;this.realtimeActivationId=e,this.beginRealtime(e,t,r,n).catch(e=>this.failRealtime(r,e))}async beginRealtime(e,t,n,r){if(await this.releaseMedia(!1),!this.isCurrentRealtime(e,t,n))return;let{realtimeNegotiate:i,realtimeEvent:a,realtimeState:o}=this.transport;if(i===void 0||a===void 0||o===void 0)throw Error(`Realtime browser transport is unavailable.`);let s;if(!this.createRealtimeSession)throw Error(`Realtime media device is unavailable.`);s=this.createRealtimeSession({muted:r,negotiate:(n,r)=>i.call(this.transport,this.clientId,t,e,n,r),onEvent:r=>{this.realtime===s&&this.isCurrentRealtime(e,t,n)&&this.enqueueRealtimePost(n,()=>a.call(this.transport,this.clientId,t,e,r))},onState:r=>{this.realtime===s&&this.isCurrentRealtime(e,t,n)&&(this.onRealtimeState(r),this.enqueueRealtimePost(n,()=>o.call(this.transport,this.clientId,t,e,r)))}}),this.realtime=s,await s.start()}closeRealtime(e=!1){let t=this.realtime,n=this.realtimeActivationId;if(t===void 0&&n===void 0)return;let r=this.activeConnectionId,i=this.realtimeGeneration;this.realtime=void 0,this.realtimeActivationId=void 0,this.realtimeGeneration+=1,t?.close(),this.onRealtimeState(void 0,e);let a=this.transport.realtimeState;n!==void 0&&r!==void 0&&a!==void 0&&this.enqueueRealtimePost(i,()=>a.call(this.transport,this.clientId,r,n,{connection:`closed`,listening:!1,speaking:!1,muted:!1}),!0)}isCurrentRealtime(e,t,n){return this.realtimeGeneration===n&&this.realtimeActivationId===e&&this.activeConnectionId===t&&!this.abortController.signal.aborted}enqueueRealtimePost(e,t,n=!1){if(this.pendingRealtimePosts>=Qt){this.failRealtime(e,Error(`Realtime browser event queue exceeded its limit.`));return}this.pendingRealtimePosts+=1;let r=this.realtimePosts.then(()=>{if(n||e===this.realtimeGeneration)return t()});this.realtimePosts=r.catch(()=>void 0),r.then(()=>{--this.pendingRealtimePosts},t=>{--this.pendingRealtimePosts,this.failRealtime(e,t)})}failRealtime(e,t){e===this.realtimeGeneration&&(this.closeRealtime(),this.onRealtimeState({connection:`failed`,listening:!1,speaking:!1,muted:!1,error:t instanceof Error?t.message:String(t)}),this.failAttempt?.(t instanceof Error?t:Error(String(t))))}async startCapture(e,t){let{captureId:n,configuration:r}=e;this.capture!==void 0&&await this.finishCapture(this.captureId??n,t,!1);let i=++this.captureGeneration;this.captureId=n,this.audioUploads=Promise.resolve(),this.audioUploadError=void 0;let a=0,o=r.activityControl===`client`?this.device.createSpeechPresenceDetector?.():void 0,s=r.activityControl===`client`&&o!==void 0?new Jt(r.endpointSilenceMs):void 0;this.speechDetector=o,this.activityLifecycle=s;try{let e=await this.device.startCapture((e,r)=>{if(i!==this.captureGeneration||this.captureId!==n||this.audioUploadError!==void 0)return;if(a+e.byteLength>$t){let e=Error(`Voice PCM upload queue exceeded its limit. The local recording is retained.`);this.audioUploadError=e,this.failActiveCapture(n,t,i,e);return}a+=e.byteLength;let c=new Uint8Array(e),l=r===void 0?c:new Uint8Array(r.speechPcm),u=r===void 0?void 0:{echoReferenceActive:r.echoReferenceActive,echoDiscriminated:r.echoDiscriminated};this.audioUploads=this.audioUploads.then(async()=>{if(a-=c.byteLength,this.audioUploadError===void 0&&i===this.captureGeneration&&this.captureId===n)try{if(l.byteLength!==c.byteLength)throw Error(`Local speech analysis must preserve the capture sample count.`);let e=await o?.push(l);if(i!==this.captureGeneration||this.captureId!==n)return;let r=s?.push(c,e,u);await this.transport.sendAudio(this.clientId,t,n,c,r)}catch(e){if(i!==this.captureGeneration||this.captureId!==n)return;let r=e instanceof Error?e:Error(String(e));tn(r)||(this.audioUploadError=r),await this.failActiveCapture(n,t,i,r)}})});if(i!==this.captureGeneration||this.captureId!==n||this.abortController.signal.aborted){await e.stop();return}this.capture=e,e.completion?.catch(e=>this.failActiveCapture(n,t,i,e instanceof Error?e:Error(String(e)))),this.resolveListening(!0)}catch(e){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e);throw await this.transport.captureStopped(this.clientId,t,n,r).catch(()=>void 0),this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),e}}async failActiveCapture(e,t,n,r){if(n!==this.captureGeneration||this.captureId!==e)return;let i=this.capture;this.capture=void 0,await i?.stop().catch(()=>void 0),n===this.captureGeneration&&this.captureId===e&&(this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),tn(r)?await this.speechDetector?.reset().catch(()=>void 0):(this.transport.captureStopped(this.clientId,t,e,`${r.name}: ${r.message}`).catch(()=>void 0),this.failAttempt?.(r)))}async finishCapture(e,t,n){let r=this.advertisedCapabilities;await this.capture?.stop(),this.capture=void 0,await this.audioUploads,await this.speechDetector?.reset().catch(()=>void 0),this.speechDetector=void 0,this.activityLifecycle=void 0;let i=an(this.device.capabilities);if(r!==void 0&&!on(r,i)&&this.transport.refreshCapabilities)try{await this.transport.refreshCapabilities(this.clientId,t,i),this.activeConnectionId===t&&(this.advertisedCapabilities=i)}catch{}if(this.audioUploadError!==void 0){let n=this.audioUploadError;throw await this.transport.captureStopped(this.clientId,t,e,`${n.name}: ${n.message}`).catch(()=>void 0),this.captureId=void 0,this.captureGeneration+=1,this.resolveCaptureEnd(),n}this.captureId=void 0,this.captureGeneration+=1,this.resolveListening(!1);try{n&&await this.transport.captureStopped(this.clientId,t,e)}finally{this.resolveCaptureEnd()}}async startPlayback(e,t){this.playbackAudioController?.abort(),this.playback?.stop(`aborted`),this.scheduleActivityReset();let n=e.delivery===`streamed`?new AbortController:void 0;this.playbackAudioController=n;let r=n?this.transport.receivePlaybackAudio?.(this.clientId,t,e.playbackId,n.signal):void 0,i;try{i=this.device.speak(e,r)}catch(r){n?.abort(),await this.transport.playbackFinished(this.clientId,t,rn(e.playbackId,r)),this.scheduleActivityReset();return}this.playback=i,i.completion.then(e=>this.transport.playbackFinished(this.clientId,t,e),n=>this.transport.playbackFinished(this.clientId,t,rn(e.playbackId,n))).catch(e=>{this.activeConnectionId!==t||this.abortController.signal.aborted||this.failAttempt?.(e instanceof Error?e:Error(String(e)))}).finally(()=>{this.playback===i&&(n?.abort(),this.playbackAudioController===n&&(this.playbackAudioController=void 0),this.playback=void 0,this.scheduleActivityReset())})}scheduleActivityReset(){let e=this.captureGeneration,t=this.activityLifecycle,n=this.speechDetector;t&&n&&(this.audioUploads=this.audioUploads.then(async()=>{e===this.captureGeneration&&t===this.activityLifecycle&&n===this.speechDetector&&(t.resetActivity(),await n.reset().catch(()=>void 0))}))}async releaseMedia(e=!0){this.captureGeneration+=1;let t=this.capture,n=this.audioUploads,r=this.speechDetector;this.capture=void 0,this.audioUploads=Promise.resolve(),this.speechDetector=void 0,this.activityLifecycle=void 0,this.captureId=void 0,this.resolveCaptureEnd(),this.audioUploadError=void 0,await t?.stop().catch(()=>void 0),this.resolveListening(!1),n.catch(()=>void 0),r?.reset().catch(()=>void 0),this.playbackAudioController?.abort(),this.playbackAudioController=void 0,this.playback?.stop(`aborted`),this.playback=void 0,e&&await this.device.close().catch(()=>void 0)}resolveListening(e){for(let t of this.listeningWaiters)t(e);this.listeningWaiters.clear()}resolveCaptureEnd(){for(let e of this.captureEndWaiters)e();this.captureEndWaiters.clear()}nextConnectionId(){let e=`:${(++this.connectionAttempt).toString(36)}`;return`${this.connectionId.slice(0,Zt-e.length)}${e}`}},ln=globalThis,un=Symbol.for(`@agimon-ai/po-voice:microphone-preferences.v2`),dn=globalThis,G=dn[un]??=m({inputs:[]}),fn=`po.voice.microphone.v1`;function pn(){try{let e=ln.localStorage.getItem(fn);if(e===null)return;let t=JSON.parse(e);if(typeof t!=`object`||!t)return;let{deviceId:n,inputs:r}=t;return n!==null&&typeof n!=`string`||!Array.isArray(r)||r.some(e=>typeof e!=`string`)?void 0:{deviceId:n,inputs:r}}catch{return}}function mn(e){try{ln.localStorage.setItem(fn,JSON.stringify(e))}catch{}}async function hn(){let e=(await ln.navigator.mediaDevices.enumerateDevices().catch(()=>[])).filter(e=>e.kind===`audioinput`&&e.deviceId&&e.deviceId!=="default"&&e.deviceId!==`communications`).map(({deviceId:e,groupId:t,label:n})=>({deviceId:e,groupId:t,label:n}));return G.update(t=>({...t,inputs:e})),e}function gn(){return G.store.state.choice===void 0?new Promise(e=>{G.update(t=>({...t,choice:(t,n)=>{G.update(e=>({...e,choice:void 0})),e({deviceId:t,remember:n})}}))}):Promise.resolve({deviceId:null,remember:!1})}function _n(){G.store.state.choice?.(null,!1)}async function vn(){let e;try{(await ln.navigator.mediaDevices.enumerateDevices().catch(()=>[])).some(e=>e.kind===`audioinput`&&e.label)||(e=await ln.navigator.mediaDevices.getUserMedia(F));let t=await hn();if(t.length<2)return F;let n=t.map(e=>e.deviceId).sort(),r=pn();if(r!==void 0&&r.inputs.join()===n.join())return r.deviceId===null?F:Re(r.deviceId);let{deviceId:i,remember:a}=await gn();return a&&mn({deviceId:i,inputs:n}),i===null?F:Re(i)}finally{e?.getTracks().forEach(e=>e.stop())}}var yn=new URL(new URL(`../assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js`,import.meta.url).href,``+import.meta.url).href,bn=2,xn=32768,Sn=2e3,Cn=300,wn=500,Tn=800,En=20,Dn=4,On=16,kn=-55,An=-50,jn=.65,Mn=.75,Nn=.25,Pn=.35,Fn=.35,In=.5,Ln=4,Rn=.98,zn=.01,Bn=N*Sn/1e3,Vn=N*Cn/1e3,Hn=N*wn/1e3,Un=Tn/1e3,Wn=N*En/1e3;function Gn(e,t,n){return Math.min(n,Math.max(t,e))}function Kn(e){if(e.byteLength===0||e.byteLength%bn!==0)throw Error(`Echo-discrimination input must contain complete PCM16 samples.`);let t=new Float32Array(e.byteLength/bn),n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t.length;e+=1)t[e]=n.getInt16(e*2,!0)/xn;return t}function qn(e){let t=new Uint8Array(e.length*bn),n=new DataView(t.buffer);for(let t=0;t<e.length;t+=1){let r=Gn(e[t]??0,-1,1);n.setInt16(t*bn,Math.round(r<0?r*xn:r*32767),!0)}return t}function Jn(e,t){let n=Math.min(e.length,Math.max(0,Bn-t.length)),r=new Float32Array(n+t.length);return n>0&&r.set(e.subarray(e.length-n)),r.set(t,n),r}function Yn(e){return e<=0?-1/0:10*Math.log10(e)}function Xn(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n*n;return t/e.length}function Zn(e){if(e.length===0)return 0;let t=0;for(let n of e)Math.abs(n)>=Rn&&(t+=1);return t/e.length}function Qn(e,t,n,r,i,a){let o=0,s=0,c=0;for(let l=0;l<i;l+=a){let i=e[n+l],a=t[r+l];i!==void 0&&a!==void 0&&(o+=i,s+=a,c+=1)}if(c<2)return 0;let l=o/c,u=s/c,d=0,f=0,p=0;for(let o=0;o<i;o+=a){let i=e[n+o],a=t[r+o];if(i===void 0||a===void 0)continue;let s=i-l,c=a-u;d+=s*c,f+=s*s,p+=c*c}let m=Math.sqrt(f*p);return m<=2**-52?0:d/m}function $n(e,t,n,r,i){let a=[],o=[];for(let s=0;s+Wn<=i;s+=Wn){let i=0,c=0;for(let a=0;a<Wn;a+=1){let o=e[n+s+a]??0,l=t[r+s+a]??0;i+=o*o,c+=l*l}a.push(Math.log10(Math.max(2**-52,i/Wn))),o.push(Math.log10(Math.max(2**-52,c/Wn)))}return a.length<3?0:Qn(Float32Array.from(a),Float32Array.from(o),0,0,a.length,1)}function er(e){return new Uint8Array(e.byteLength)}var tr=class{references=[];microphoneHistory=new Float32Array;referenceHistory=new Float32Array;beginPlayback(e,t,n){if(e&&t.length!==0&&Number.isFinite(n)){for(let e of this.references)e.endedAt===void 0&&this.finishReference(e,n);this.references.push({playbackId:e,samples:t,startedAt:n})}}endPlayback(e,t){if(!Number.isFinite(t))return;let n=this.references.slice().reverse().find(t=>t.playbackId===e);n!==void 0&&n.endedAt===void 0&&this.finishReference(n,t)}process(e,t){let n=Kn(e);if(!Number.isFinite(t))return this.unavailable(e,n);let r=t-n.length/N;this.pruneReferences(r);let i=this.renderReference(r,n.length);if(this.microphoneHistory=Jn(this.microphoneHistory,n),this.referenceHistory=Jn(this.referenceHistory,i.samples),!i.tracked)return{speechPcm:new Uint8Array(e),referenceActive:!1,speechDiscriminated:!1,state:`unavailable`};let a=Math.min(Vn,this.microphoneHistory.length),o=this.microphoneHistory.length-a,s=this.referenceHistory.length-a,c=Math.min(Hn,s),l=Math.max(0,s-c),u=this.referenceHistory.subarray(l),d=this.microphoneHistory.subarray(o),f=Yn(Xn(d));if(Yn(Xn(u))<kn)return f>=An?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`};if(a<Vn||c<=0||Zn(d)>zn)return{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`};let p=0,m=0;for(let e=0;e<=c;e+=On){let t=Qn(this.microphoneHistory,this.referenceHistory,o,s-e,a,Dn);Math.abs(t)>Math.abs(m)&&(m=t,p=e)}let h=Math.max(0,p-On),g=Math.min(c,p+On);for(let e=h;e<=g;e+=1){let t=Qn(this.microphoneHistory,this.referenceHistory,o,s-e,a,2);Math.abs(t)>Math.abs(m)&&(m=t,p=e)}let _=s-p,v=Math.abs($n(this.microphoneHistory,this.referenceHistory,o,_,a)),y=Math.abs(m),b=0,x=0,S=0;for(let e=0;e<a;e+=1){let t=this.microphoneHistory[o+e]??0,n=this.referenceHistory[_+e]??0;b+=t*n,x+=n*n,S+=t*t}let C=Gn(x<=2**-52?0:b/x,0,Ln),w=0;for(let e=0;e<a;e+=1){let t=(this.microphoneHistory[o+e]??0)-C*(this.referenceHistory[_+e]??0);w+=t*t}let ee=S<=2**-52?0:w/S,T=new Float32Array(n.length),E=this.microphoneHistory.length-n.length,D=this.referenceHistory.length-n.length-p;for(let e=0;e<n.length;e+=1)T[e]=(this.microphoneHistory[E+e]??0)-C*(this.referenceHistory[D+e]??0);let O=qn(T),k=Yn(Xn(T));return m>=jn&&ee<=Fn?{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:m>=jn&&v<Mn&&ee>=In&&k>=An?{speechPcm:O,referenceActive:!0,speechDiscriminated:!0,state:`mixed`}:y<Nn&&v<Pn&&f>=An?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:v>=Mn?{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:{speechPcm:er(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`}}resetCapture(){this.microphoneHistory=new Float32Array,this.referenceHistory=new Float32Array}reset(){this.references=[],this.resetCapture()}unavailable(e,t=Kn(e)){return this.microphoneHistory=Jn(this.microphoneHistory,t),this.referenceHistory=Jn(this.referenceHistory,new Float32Array(t.length)),{speechPcm:new Uint8Array(e),referenceActive:!1,speechDiscriminated:!1,state:`unavailable`}}renderReference(e,t){let n=new Float32Array(t),r=!1;for(let i of this.references){let a=i.startedAt+i.samples.length/N,o=Math.min(i.endedAt??a,a);e<o+Un&&e+t/16e3>=i.startedAt&&(r=!0);let s=Math.round((e-i.startedAt)*N),c=Math.round((o-i.startedAt)*N);for(let e=0;e<t;e+=1){let t=s+e;t<0||t>=c||(n[e]+=i.samples[t]??0)}}return{samples:n,tracked:r}}finishReference(e,t){let n=e.startedAt+e.samples.length/N;e.endedAt=Math.max(e.startedAt,Math.min(t,n));let r=Math.ceil((e.endedAt-e.startedAt)*N),i=Math.max(0,r-Hn-Vn);e.samples=new Float32Array(e.samples.subarray(i,r)),e.startedAt+=i/N}pruneReferences(e){this.references=this.references.filter(t=>t.endedAt===void 0||e<=t.endedAt+Un)}},nr=5e3,rr=class extends Error{};function ir(e){return typeof e==`object`&&!!e&&Number.isSafeInteger(e.id)}var ar=class{worker;onTerminalFailure;responseTimeoutMs;nextRequestId=0;generation=0;operation=Promise.resolve();pending=new Map;closed=!1;failure;constructor(e,t=()=>void 0,n=nr){this.worker=e,this.onTerminalFailure=t,this.responseTimeoutMs=n,e.onmessage=e=>{if(!ir(e.data)){this.failTerminal(Error(`Silero worker returned a malformed response.`));return}let t=this.pending.get(e.data.id);t!==void 0&&(e.data.error===void 0?(this.pending.delete(e.data.id),t.timer!==void 0&&clearTimeout(t.timer),t.resolve(e.data.result)):this.failTerminal(Error(e.data.error)))},e.onerror=e=>this.failTerminal(Error(e.message||`Silero worker failed.`))}async initialize(e){if(await this.enqueue(()=>this.request({type:`initialize`,modelUrl:e}))!==!0){let e=Error(`Silero worker returned an invalid initialization response.`);throw this.failTerminal(e),e}}async push(e){let t=this.generation,n=new Uint8Array(e),r;try{r=await this.enqueue(()=>this.request({type:`push`,pcm:n.buffer},[n.buffer],this.responseTimeoutMs))}catch(e){if(e instanceof rr)return[];throw e}if(t!==this.generation)return[];if(!Array.isArray(r))throw Error(`Silero worker returned invalid speech windows.`);return r}async reset(){this.generation+=1,await this.enqueue(()=>this.request({type:`reset`},void 0,this.responseTimeoutMs))}async close(){this.closed||(this.closed=!0,this.generation+=1,this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.failAll(Error(`Silero worker closed.`)))}enqueue(e){let t=this.operation.then(e,e);return this.operation=t,t}request(e,t,n){if(this.closed)return Promise.reject(this.failure??Error(`Silero worker is closed.`));let r=++this.nextRequestId;return new Promise((i,a)=>{let o={resolve:i,reject:a};n!==void 0&&(o.timer=setTimeout(()=>{this.pending.has(r)&&this.failTerminal(new rr(`Silero worker response timed out.`))},n)),this.pending.set(r,o),this.worker.postMessage({id:r,...e},t)})}failTerminal(e){this.closed||(this.failure=e,this.closed=!0,this.generation+=1,this.worker.onmessage=null,this.worker.onerror=null,this.worker.terminate(),this.failAll(e),this.onTerminalFailure())}failAll(e){for(let t of this.pending.values())t.timer!==void 0&&clearTimeout(t.timer),t.reject(e);this.pending.clear()}},or=new URL(new URL(`../assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx`,import.meta.url).href,``+import.meta.url).href,sr=new URL(new URL(`../assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs`,import.meta.url).href,``+import.meta.url).href,cr=4096,lr=100,ur=`po-voice-capture`,dr=180,fr=5e3,pr=1e4,mr=.1,hr=10,K=2,gr=32767,_r=N*K*lr/1e3,vr=1e-8,yr=.05,br=N*300/1e3;function xr(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.samples instanceof Float32Array&&typeof t.capturedAt==`number`}function Sr(){return typeof window<`u`&&typeof window.speechSynthesis?.speak==`function`}function Cr(){return typeof AudioContext==`function`}function wr(){if(typeof SpeechSynthesisUtterance==`function`)return SpeechSynthesisUtterance;if(typeof window>`u`)return;let e=window.SpeechSynthesisUtterance;return typeof e==`function`?e:void 0}var Tr=class{sourceRate;sourceIndex=0;nextOutputAt=0;constructor(e){if(this.sourceRate=e,!Number.isFinite(e)||e<=0)throw Error(`Audio source rate must be positive.`)}push(e){let t=[],n=this.sourceRate/N;for(let r=0;r<e.length;r+=1){let i=this.sourceIndex+r;for(;this.nextOutputAt<=i;){let i=Math.max(-1,Math.min(1,e[r]??0));t.push(Math.round(i<0?i*32768:i*gr)),this.nextOutputAt+=n}}this.sourceIndex+=e.length;let r=new Uint8Array(t.length*2),i=new DataView(r.buffer);return t.forEach((e,t)=>i.setInt16(t*2,e,!0)),r}},Er=class{synthesis;utterance;playbackId;completion;requestedOutcome;settleCompletion;settled=!1;ducked=!1;fadeTimer;restoreTimer;startTimer;constructor(e,t,n){this.synthesis=e,this.utterance=t,this.playbackId=n,this.completion=new Promise(e=>{this.settleCompletion=e}),t.onstart=()=>{this.startTimer!==void 0&&clearTimeout(this.startTimer),this.startTimer=void 0},t.onend=()=>this.settle(this.requestedOutcome??`completed`),t.onerror=e=>this.settle(this.requestedOutcome??`failed`,e.error||`Browser speech synthesis failed.`),this.startTimer=setTimeout(()=>{this.synthesis.cancel(),this.settle(`failed`,`Browser speech synthesis did not start.`)},fr)}stop(e){this.settled||(this.requestedOutcome=e,this.synthesis.cancel(),this.settle(e))}duck(e,t,n){if(this.settled||this.ducked)return;this.ducked=!0;let r=Math.max(0,Math.min(1,e));this.fadeTo(r,Math.max(0,t),()=>{this.restoreTimer=setTimeout(()=>{this.restoreTimer=void 0,this.fadeTo(1,600,()=>{this.ducked=!1})},Math.max(0,n))})}fadeTo(e,t,n){this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.fadeTimer=void 0;let r=this.utterance.volume,i=Math.max(1,Math.ceil(t/50)),a=0,o=()=>{a+=1,this.utterance.volume=r+(e-r)*Math.min(1,a/i),!(a<i)&&(this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.fadeTimer=void 0,n())};t===0?o():this.fadeTimer=setInterval(o,t/i)}settle(e,t){this.settled||(this.settled=!0,this.fadeTimer!==void 0&&clearInterval(this.fadeTimer),this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.startTimer!==void 0&&clearTimeout(this.startTimer),this.fadeTimer=void 0,this.restoreTimer=void 0,this.startTimer=void 0,this.utterance.onstart=null,this.utterance.onend=null,this.utterance.onerror=null,this.settleCompletion({playbackId:this.playbackId,outcome:e,...t?{error:t}:{}}))}},Dr=class{context;playbackId;echoDiscriminator;completion;source;gain;settled=!1;settleCompletion;restoreTimer;startedAt;constructor(e,t,n,r){this.context=e,this.playbackId=n,this.echoDiscriminator=r,this.completion=new Promise(e=>{this.settleCompletion=e}),this.start(t)}stop(e){this.settled||(this.source!==void 0&&(this.source.onended=null),this.source?.stop(),this.settle(e))}duck(e,t,n){this.settled||this.gain===void 0||(this.gain.gain.value=Math.max(0,Math.min(1,e)),this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.restoreTimer=setTimeout(()=>{this.restoreTimer=void 0,this.gain!==void 0&&(this.gain.gain.value=1)},Math.max(0,n)))}async start(e){try{let t=await e;if(this.settled)return;if(t.byteLength===0||t.byteLength%K!==0)throw Error(`Streamed narration audio is empty or incomplete.`);if(this.context.state!==`running`)throw Error(`Browser audio playback is suspended. Tap the voice control.`);let n=new Float32Array(t.byteLength/K),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let e=0;e<n.length;e+=1)n[e]=r.getInt16(e*2,!0)/32768;let i=this.context.createBuffer(1,n.length,N);i.copyToChannel(n,0);let a=this.context.createBufferSource(),o=this.context.createGain();o.gain.value=1,a.buffer=i,a.onended=()=>this.settle(`completed`),a.connect(o),o.connect(this.context.destination),this.source=a,this.gain=o;let s=this.context.currentTime;this.startedAt=s,this.echoDiscriminator.beginPlayback(this.playbackId,i.getChannelData(0),s),a.start(s)}catch(e){let t=e instanceof Error?`${e.name}: ${e.message}`:String(e);this.settle(`failed`,t)}}settle(e,t){this.settled||(this.settled=!0,this.restoreTimer!==void 0&&clearTimeout(this.restoreTimer),this.source!==void 0&&(this.source.onended=null),this.startedAt!==void 0&&this.echoDiscriminator.endPlayback(this.playbackId,this.context.currentTime),this.source?.disconnect(),this.gain?.disconnect(),this.source=void 0,this.gain=void 0,this.settleCompletion({playbackId:this.playbackId,outcome:e,...t?{error:t}:{}}))}},Or=class{rebindProtocolSupported;microphoneConstraints;capabilities={capture:typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0,playback:Sr()||Cr(),captureActivity:!1,autonomousOrchestration:!1,playbackDucking:Sr()||Cr(),realtime:typeof RTCPeerConnection==`function`&&typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0};captureGeneration=0;captureDeviceId;constructor(e=!1,t=async()=>F){this.rebindProtocolSupported=e,this.microphoneConstraints=t}armUserGesture(){this.listenForMediaUnlock()}stream;context;workletInstalled=!1;activeCapture;activePlayback;speechDetector;preparingSpeechDetector;speechPreparation;listeningForMediaUnlock=!1;speechWarmup;speechWarmupTimer;echoDiscriminator=new tr;unlockMedia=()=>{if(typeof AudioContext<`u`)try{this.context??=new AudioContext;let e=this.context;e.resume().then(()=>{e.state===`running`&&this.stopListeningForMediaUnlock()}).catch(()=>void 0)}catch{}this.warmSpeechSynthesis()};async prepare(){this.armUserGesture(),this.speechPreparation??=this.prepareSpeechDetector(),await this.speechPreparation}createSpeechPresenceDetector(){return this.speechDetector}async startCapture(e){if(!this.capabilities.capture)throw Error(`This browser cannot capture microphone audio.`);if(this.activeCapture!==void 0)throw Error(`Browser microphone capture is already active.`);let t=this.captureGeneration,n=await this.microphoneConstraints();if(t!==this.captureGeneration)throw Error(`Microphone capture was cancelled.`);let r=n.audio.deviceId?.exact;if(this.stream&&this.captureDeviceId!==r){for(let e of this.stream.getTracks())e.stop();this.stream=void 0}if(this.stream??=await navigator.mediaDevices.getUserMedia(n),t!==this.captureGeneration){for(let e of this.stream.getTracks())e.stop();throw this.stream=void 0,Error(`Microphone capture was cancelled.`)}if(this.captureDeviceId=r,this.context??=new AudioContext,await this.context.resume(),this.context.state!==`running`)throw Error(`Browser audio capture is suspended. Tap the voice control and try again.`);this.stopListeningForMediaUnlock();let i=this.stream,a=this.context.createMediaStreamSource(i),o=this.context.createGain();o.gain.value=vr;let s=new Tr(this.context.sampleRate);this.echoDiscriminator.resetCapture();let c=[],l=0,u,d=0,f,p=0,m=t=>{let n=new Uint8Array(t),r=0;for(;r<t;){let e=c[0];if(e===void 0)break;let i=Math.min(e.byteLength,t-r);n.set(e.subarray(0,i),r),r+=i,i===e.byteLength?c.shift():c[0]=e.subarray(i)}l-=t;let i=t/K,a=(u??this.context.currentTime)+(d+i)/N;d+=i;let o=this.echoDiscriminator.process(n,a),s=p>0;p=Math.max(0,p-i),e(n,{speechPcm:s?new Uint8Array(n.byteLength):o.speechPcm,echoReferenceActive:o.referenceActive,echoDiscriminated:!s&&o.speechDiscriminated})},h=(e,t)=>{let n=t!==void 0&&Number.isFinite(t)?t:void 0;n!==void 0&&f!==void 0&&Math.abs(n-f)>yr&&(this.echoDiscriminator.resetCapture(),p=l/K+br,u=n-(d+l/K)/N),n!==void 0&&(f=n+e.length/this.context.sampleRate),u??=n??this.context.currentTime-e.length/this.context.sampleRate;let r=s.push(e);if(r.byteLength!==0)for(c.push(r),l+=r.byteLength;l>=_r;)m(_r)},g,_;if(typeof AudioWorkletNode<`u`&&this.context.audioWorklet!==void 0){this.workletInstalled||=(await this.context.audioWorklet.addModule(yn),!0);let e=new AudioWorkletNode(this.context,ur);e.port.onmessage=e=>{xr(e.data)&&h(e.data.samples,e.data.capturedAt)},g=e,_=()=>{e.port.onmessage=null,e.port.close()}}else{let e=this.context.createScriptProcessor(cr,1,1);e.onaudioprocess=e=>h(e.inputBuffer.getChannelData(0),e.playbackTime),g=e,_=()=>{e.onaudioprocess=null}}a.connect(g),g.connect(o),o.connect(this.context.destination);let v=!1,y,b,x=new Promise((e,t)=>{y=e,b=t});for(let e of i.getTracks())e.onended=()=>b(Error(`The selected microphone was disconnected.`));let S={completion:x,stop:async()=>{if(!v){v=!0;for(let e of i.getTracks())e.onended=null;if(y(),_(),l>0&&m(l),a.disconnect(),g.disconnect(),o.disconnect(),!this.rebindProtocolSupported||this.stream!==i)for(let e of i.getTracks())e.stop();!this.rebindProtocolSupported&&this.stream===i&&(this.stream=void 0),this.activeCapture===S&&(this.activeCapture=void 0)}}};return this.activeCapture=S,S}speak(e,t){if(!this.capabilities.playback)throw Error(`This browser cannot play speech narration.`);this.activePlayback?.stop(`aborted`);let n;if(e.delivery===`streamed`){if(t===void 0)throw Error(`Streamed narration audio is unavailable.`);if(typeof AudioContext!=`function`)throw Error(`This browser cannot play streamed narration audio.`);if(this.context===void 0||this.context.state!==`running`)throw Error(`Browser audio playback is not unlocked. Tap the voice control and try again.`);n=new Dr(this.context,t,e.playbackId,this.echoDiscriminator)}else{this.finishSpeechWarmup(!1);let t=window.speechSynthesis,r=wr();if(r===void 0)throw Error(`This browser does not expose speech utterance playback.`);t.resume();let i=new r(e.text);e.rate!==void 0&&(i.rate=Math.max(mr,Math.min(hr,e.rate/dr))),e.voice&&(i.voice=t.getVoices().find(t=>t.name===e.voice||t.voiceURI===e.voice)??null),n=new Er(t,i,e.playbackId),t.speak(i)}return this.activePlayback=n,n.completion.finally(()=>{this.activePlayback===n&&(this.activePlayback=void 0)}),n}async close(){this.captureGeneration+=1;let e=this.speechDetector,t=this.preparingSpeechDetector,n=this.speechPreparation;this.speechDetector=void 0,this.preparingSpeechDetector=void 0,this.speechPreparation=void 0,this.capabilities.captureActivity=!1,this.capabilities.autonomousOrchestration=!1,await e?.close().catch(()=>void 0),t!==e&&await t?.close().catch(()=>void 0),await n?.catch(()=>void 0),this.stopListeningForMediaUnlock(),this.finishSpeechWarmup(!0),await this.activeCapture?.stop(),this.activePlayback?.stop(`aborted`);for(let e of this.stream?.getTracks()??[])e.stop();this.stream=void 0,this.context!==void 0&&this.context.state!==`closed`&&await this.context.close(),this.echoDiscriminator.reset(),this.context=void 0,this.workletInstalled=!1}listenForMediaUnlock(){this.listeningForMediaUnlock||typeof window>`u`||!this.capabilities.capture&&!this.capabilities.playback||(this.listeningForMediaUnlock=!0,window.addEventListener(`pointerdown`,this.unlockMedia,{capture:!0,passive:!0}),window.addEventListener(`keydown`,this.unlockMedia,{capture:!0}))}stopListeningForMediaUnlock(){this.listeningForMediaUnlock&&typeof window<`u`&&(this.listeningForMediaUnlock=!1,window.removeEventListener(`pointerdown`,this.unlockMedia,!0),window.removeEventListener(`keydown`,this.unlockMedia,!0))}warmSpeechSynthesis(){if(!Sr()||this.activePlayback!==void 0||this.speechWarmup!==void 0)return;let e=window.speechSynthesis,t=wr();if(t===void 0||(e.resume(),e.speaking||e.pending))return;let n=new t(`a`);n.volume=.01,n.rate=hr,n.onend=()=>this.finishSpeechWarmup(!1),n.onerror=()=>this.finishSpeechWarmup(!1),this.speechWarmup=n,this.speechWarmupTimer=setTimeout(()=>this.finishSpeechWarmup(!0),pr),e.speak(n)}finishSpeechWarmup(e){let t=this.speechWarmup;t!==void 0&&(this.speechWarmupTimer!==void 0&&clearTimeout(this.speechWarmupTimer),this.speechWarmupTimer=void 0,this.speechWarmup=void 0,t.onend=null,t.onerror=null,e&&window.speechSynthesis.cancel())}async prepareSpeechDetector(){if(typeof Worker>`u`||typeof WebAssembly>`u`)return;let e;try{if(e=new ar(new Worker(sr,{type:`module`,name:`po-silero-vad`}),()=>{(this.preparingSpeechDetector===e||this.speechDetector===e)&&(this.preparingSpeechDetector===e&&(this.preparingSpeechDetector=void 0),this.speechDetector===e&&(this.speechDetector=void 0),this.capabilities.captureActivity=!1,this.capabilities.autonomousOrchestration=!1)}),this.preparingSpeechDetector=e,await e.initialize(or),this.preparingSpeechDetector!==e){await e.close().catch(()=>void 0);return}this.preparingSpeechDetector=void 0,this.speechDetector=e,this.capabilities.captureActivity=!0,this.capabilities.autonomousOrchestration=this.rebindProtocolSupported}catch{this.preparingSpeechDetector===e&&(this.preparingSpeechDetector=void 0),this.speechDetector===e&&(this.speechDetector=void 0),await e?.close().catch(()=>void 0)}}};function kr(){let e=ke({header:_()});if(e.status!==`ok`||!e.metadata.instanceId)throw Error(`Voice requires the shell client instance identity.`);return e.metadata.instanceId}var Ar=`application/json`,jr=6e4,Mr=200,Nr=8e3,Pr=2e4;function Fr(e){return typeof e.eventEpoch==`string`&&e.eventEpoch.length>0&&e.eventEpoch.length<=Mr&&Number.isSafeInteger(e.heartbeatMs)&&(e.heartbeatMs??0)>0&&(e.heartbeatMs??0)<=jr?{eventEpoch:e.eventEpoch,heartbeatMs:e.heartbeatMs}:void 0}function q(e){return Object.assign(Error(e.error===``?`Voice media request failed with status ${String(e.status)}.`:e.error),{status:e.status,conflict:e.data})}function Ir(e){if(!e.ok)throw q(e);if(`standby`in e.data)throw Object.assign(Error(`Another client owns voice media for this session.`),{status:409,standby:!0,conflict:e.data.conflict});return e.data}async function Lr(e){let t=`Voice media request failed with status ${String(e.status)}.`,n;try{let r=await e.json();n=r,typeof r==`object`&&r&&`error`in r&&typeof r.error==`string`&&(t=r.error)}catch{}return Object.assign(Error(t),{status:e.status,conflict:n})}function J(e){return{method:`POST`,headers:{"content-type":Ar},body:JSON.stringify(e)}}function Rr(e,t={}){let n=new URL(e,`http://po.local`);for(let[e,r]of Object.entries(t))r!==void 0&&n.searchParams.set(e,String(r));return`${n.pathname}${n.search}`}function zr(e){try{e?.body?.cancel().catch(()=>void 0)}catch{}}async function Br(e,n,r,i,a,o=(e,n)=>t.fetch(e,n)){let s=new AbortController,c=a??s.signal,l,u=!1,d,f,p=new Promise((e,t)=>{f=t}),m=e=>{u||(u=!0,d=e,s.abort(e),zr(l),f(e))},h=()=>m(a?.reason??new DOMException(`Voice media control request was aborted.`,`AbortError`)),g=setTimeout(()=>m(Error(`Voice media control request timed out.`)),r);a?.addEventListener(`abort`,h,{once:!0});let _;try{_=o(e,{...n,signal:c})}catch(e){throw clearTimeout(g),a?.removeEventListener(`abort`,h),e}let v=_.then(async e=>{if(l=e,u)throw zr(e),d;return i(e)});try{return a?.aborted&&h(),await Promise.race([v,p])}finally{clearTimeout(g),a?.removeEventListener(`abort`,h)}}var Vr=class{sessionId;claimForActivation;takeoverGeneration;push;controlLocation;binding;constructor(e,t=!1,n){this.sessionId=e,this.claimForActivation=t,this.takeoverGeneration=n}media(){if(this.sessionId===null)throw Error(`PCM routes are session-scoped, not global live media.`);return H.session(this.sessionId)}remote(){return this.sessionId!==null&&/^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(this.sessionId)}async fetch(e,n,r={}){if(!this.remote())return t.fetch(n,r);let i=new Headers(r.headers),a=ke({header:_()});a.status===`ok`&&i.set(be,Oe(a.metadata));let o=new Request(new URL(e,`http://po.local`),{...r,headers:i}),s=new Uint8Array(await o.arrayBuffer()),c=new URL(o.url).searchParams.get(`connectionId`)??void 0;if(!c&&s.byteLength>0)try{let e=JSON.parse(new TextDecoder().decode(s));typeof e.connectionId==`string`&&(c=e.connectionId)}catch{c=void 0}if(!c)throw Error(`Paired Voice request has no connection binding.`);if(!this.binding||this.binding.connectionId!==c||this.binding.expiresAt<=Date.now()+Nr){let e=await V.host.relayBinding({body:{target:this.sessionId,connectionId:c}});if(!e.ok)throw q(e);let t=e.data;if(typeof t.binding!=`string`||!Number.isSafeInteger(t.expiresAt))throw Error(`Paired Voice media binding is invalid.`);this.binding={id:t.binding,connectionId:c,expiresAt:t.expiresAt}}let l=``;for(let e of s)l+=String.fromCharCode(e);let u=await V.host.relay({query:{binding:this.binding.id},body:{targetSessionId:``,method:o.method===`GET`?`GET`:`POST`,path:e,headers:[...o.headers.entries()],body:btoa(l)}});if(!u.ok)throw q(u);let d=u.data;if(!Number.isSafeInteger(d.status)||!Array.isArray(d.headers)||typeof d.body!=`string`)throw Error(`Paired Voice relay response is invalid.`);let f=atob(d.body),p=Uint8Array.from(f,e=>e.charCodeAt(0));return new Response(p.byteLength===0?null:p,{status:d.status,headers:d.headers})}async remoteResult(e,t,n){let r=await this.fetch(e,t,n),i;try{i=r.status===204?void 0:await r.json()}catch{i=void 0}return r.ok?{ok:!0,status:r.status,data:i,response:r}:{ok:!1,status:r.status,error:typeof i==`object`&&i&&`error`in i&&typeof i.error==`string`?i.error:`Voice media request failed with status ${String(r.status)}.`,data:i,response:r}}async connect(e,n,r){this.push=void 0;let i=t.active()?`remote`:`local`,a=this.claimForActivation;this.claimForActivation=!1;let o=this.takeoverGeneration;this.takeoverGeneration=void 0;let s=Ir(await this.declareClient(e,n,r,i,a,o));return this.controlLocation=i,this.push=this.sessionId===null?void 0:Fr(s),s}async refreshCapabilities(e,t,n){let r=this.controlLocation;if(r===void 0)throw Error(`Voice media client is not connected.`);let i=this.claimForActivation;this.claimForActivation=!1,Ir(await this.declareClient(e,t,n,r,i))}async disconnect(e,t){try{let n={clientId:e,connectionId:t},r=this.sessionId===null?await H.host.clientDisconnect({body:n}):this.remote()?await this.remoteResult(P.clientDisconnect,``,J(n)):await this.media().clientDisconnect({body:n});if(!r.ok&&r.status!==409)throw q(r)}finally{this.push=void 0,this.controlLocation=void 0,this.binding=void 0}}async nextEvent(e,t,n,r){let i=this.push,a=this.sessionId;if(i===void 0||a===null)return this.fetchEvent(e,t,n,r,!1);for(;!r.aborted;){let o=await st(a,i.eventEpoch,n,i.heartbeatMs,r);if(r.aborted)return;let s=o??await this.heartbeat(e,t);if(s.eventEpoch!==i.eventEpoch)throw Error(`Voice media broker changed.`);if(s.sequence<=n)continue;let c=await this.fetchEvent(e,t,n,r,!0);if(c===void 0)throw Error(`Voice media wake could not be resolved.`);return c}}declareClient(e,t,n,r,i=!1,a){let o={version:7,clientId:e,connectionId:t,clientKind:`browser`,controlLocation:r,capabilities:n,acceptStandby:!0,...i?{claimForActivation:!0}:{},...a===void 0?{}:{takeoverGeneration:a}};return this.sessionId===null?H.host.clientConnect({body:o}):this.remote()?this.remoteResult(P.clientConnect,``,J(o)):this.media().clientConnect({body:o})}async fetchEvent(e,t,n,r,i){let a=Rr(P.clientEvents,{clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}}),o={clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}},s=this.sessionId===null?H.host.clientEvents.url({query:o}):this.remote()?``:this.media().clientEvents.url({query:o});return Br(s,{},Nr,async e=>{if(e.status!==204){if(!e.ok)throw await Lr(e);return await e.json()}},r,(e,t)=>this.fetch(a,s,t))}heartbeat(e,t){let n=P.clientHeartbeat,r=this.sessionId===null?H.host.clientHeartbeat.url():this.remote()?``:this.media().clientHeartbeat.url();return Br(r,J({clientId:e,connectionId:t}),Nr,async e=>{if(!e.ok)throw await Lr(e);let t=ze(await e.json());if(t===null)throw Error(`Voice media heartbeat response is invalid.`);return t},void 0,(e,t)=>this.fetch(n,r,t))}async sendAudio(e,t,n,r,i){let a={clientId:e,connectionId:t,captureId:n},o={"content-type":Ae,...i===void 0?{}:{[je]:i.state,[Me]:String(i.levelDbfs),[Ne]:String(i.elapsedMs),...i.epoch===void 0?{}:{[Pe]:String(i.epoch)},...i.classifiedSpeechMs===void 0?{}:{[Fe]:String(i.classifiedSpeechMs)},...i.echoDiscriminatedSpeechMs===void 0?{}:{[Ie]:String(i.echoDiscriminatedSpeechMs)}}},s=new Blob([new Uint8Array(r)],{type:Ae}),c=this.remote()?await this.remoteResult(Rr(P.clientAudio,a),``,{method:`POST`,headers:o,body:s}):await this.media().clientAudio({query:a,headers:o,body:s});if(!c.ok)throw q(c)}async captureStopped(e,t,n,r){let i={clientId:e,connectionId:t,captureId:n,...r===void 0?{}:{error:r}},a=this.remote()?await this.remoteResult(P.clientCaptureStopped,``,J(i)):await this.media().clientCaptureStopped({body:i});if(!a.ok)throw q(a)}async receivePlaybackAudio(e,t,n,r){let i=[],a=0,o=Rr(P.clientPlaybackAudio,{clientId:e,connectionId:t,playbackId:n}),s=this.remote()?``:this.media().clientPlaybackAudio.url({query:{clientId:e,connectionId:t,playbackId:n}});for(;!r.aborted;){let e=await this.fetch(o,s,{signal:r});if(e.status===200&&e.headers.get(`content-type`)?.startsWith(`application/vnd.po.pcm-s16le`)){let t=new Uint8Array(await e.arrayBuffer());i.push(t),a+=t.byteLength}else{if(e.status===204&&e.headers.get(`x-po-playback-state`)===`sealed`){let e=new Uint8Array(a),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;return e}if(e.status!==204)throw await Lr(e)}}throw new DOMException(`Voice playback audio was aborted.`,`AbortError`)}async playbackFinished(e,t,n){let r={clientId:e,connectionId:t,...n},i=this.remote()?await this.remoteResult(P.clientPlaybackResult,``,J(r)):await this.media().clientPlaybackResult({body:r});if(!i.ok)throw q(i)}async realtimeNegotiate(e,t,n,r,i){let a=B.clientNegotiate,o=this.sessionId===null?H.host.realtimeNegotiate.url():this.remote()?``:this.media().realtimeNegotiate.url();return Br(o,J({clientId:e,connectionId:t,activationId:n,sdp:r}),Pr,async e=>{if(!e.ok)throw await Lr(e);let t=await e.json();if(typeof t!=`object`||!t||typeof t.sdp!=`string`)throw Error(`Realtime negotiation response is invalid.`);return t.sdp},i,(e,t)=>this.fetch(a,o,t))}async realtimeEvent(e,t,n,r){let i=this.sessionId===null?H.host.realtimeEvent.url():this.remote()?``:this.media().realtimeEvent.url();await this.postRealtime(B.clientEvent,i,{clientId:e,connectionId:t,activationId:n,event:r})}async realtimeState(e,t,n,r){let i=this.sessionId===null?H.host.realtimeState.url():this.remote()?``:this.media().realtimeState.url();await this.postRealtime(B.clientState,i,{clientId:e,connectionId:t,activationId:n,state:r})}postRealtime(e,t,n){return Br(t,J(n),Nr,async e=>{if(!e.ok)throw await Lr(e)},void 0,(n,r)=>this.fetch(e,t,r))}},Hr=class{device=new Or(!0,vn);clientId=kr();ownedSessionId=null;handoffActive=!1;releaseAudioPending=!1;selectionGeneration=0;client;globalClient;boundSessionId;operation=Promise.resolve();unsubscribe;closeOnPageHide=()=>this.close();closed=!1;openSession;constructor(){this.device.armUserGesture();let e=()=>this.select(L.store.state),t=L.store.subscribe(e),n=et.store.subscribe(e);this.unsubscribe=()=>{t.unsubscribe(),n.unsubscribe()},window.addEventListener(`pagehide`,this.closeOnPageHide,{once:!0}),this.select(L.store.state)}focus(e){}close(){if(this.closed)return;this.closed=!0,_n(),window.removeEventListener(`pagehide`,this.closeOnPageHide),this.unsubscribe(),this.client?.endRealtime(),this.globalClient?.endRealtime();let e=async()=>{try{await this.detach(),await this.globalClient?.stop(!1),this.globalClient=void 0}finally{await this.device.close()}};this.operation=this.operation.then(e,e).then(()=>void 0,()=>void 0)}async prepareLiveActivation(e){if(this.closed)throw Error(`Voice media page is closed.`);if(e!==void 0&&this.globalClient){let e=this.globalClient;this.globalClient=void 0,await e.stop(!1)}if(this.globalClient||this.startGlobalClient(!0,e),!this.globalClient)throw Error(`Global Voice media is unavailable.`);return this.globalClient.waitForConnection()}async prepareSessionActivation(e,t){if(this.closed)throw Error(`Voice media page is closed.`);if(await this.operation,(t!==void 0||R.store.state?.phase===`conflict`)&&await this.detach(),await this.attach(e,this.selectionGeneration,!0,t),!this.client)throw Error(`Session Voice media is unavailable.`);return this.client.waitForConnection()}startGlobalClient(e=!1,t){try{if(this.closed)return;let n={capabilities:{capture:!1,playback:!1,captureActivity:!1,autonomousOrchestration:!1,realtime:!0},async startCapture(){throw Error(`Global live Voice does not accept PCM capture.`)},speak(){throw Error(`Global live Voice does not accept PCM playback.`)},async close(){}},r;r=new cn(this.clientId,`global-${crypto.randomUUID()}`,new Vr(null,e,t),n,(e,n)=>{if(this.globalClient!==r)return;e===`conflict`&&this.reportOwnership(null,n,t);let i=R.store.state;i?.sessionId===null&&(e===`disconnected`&&i.realtime?.connection!==`failed`?R.reset():e!==`disconnected`&&R.update(()=>({...i,phase:e})))},(e,t)=>{if(this.globalClient!==r)return;if(e===void 0){if(R.store.state?.sessionId===null&&R.reset(),z.store.state?.sessionId===null&&z.reset(),t)return;this.globalClient=void 0,r.stop(!1);return}let n=R.store.state;R.update(()=>({sessionId:null,phase:n?.sessionId===null?n.phase:`connected`,realtime:e,realtimeOutputInterrupted:n?.sessionId===null?n.realtimeOutputInterrupted:void 0})),z.update(()=>({sessionId:null,mute:e=>this.controlGlobal(e?`mute`:`unmute`),interrupt:()=>{r.interruptRealtime(),this.controlGlobal(`interrupt`);let e=R.store.state;e?.sessionId===null&&R.update(()=>({...e,realtimeOutputInterrupted:!0}))},end:()=>{r.endRealtime(),this.controlGlobal(`end`)}}))},e=>new Rt(e,vn),e=>this.openSession?.(e)),this.globalClient=r,r.start()}catch(e){if(this.closed||R.store.state?.sessionId)return;let t=e instanceof Error?e.message:String(e);R.update(()=>({sessionId:null,phase:`conflict`,realtime:{connection:`failed`,listening:!1,speaking:!1,muted:!1,error:t}}))}}controlGlobal(e){V.host.liveControl({body:{action:e}}).then(e=>{if(!e.ok)throw Error(e.error)}).catch(e=>{let t=R.store.state;(t===void 0||t.sessionId===null)&&R.update(()=>({sessionId:null,phase:`conflict`,realtime:{connection:`failed`,listening:!1,speaking:!1,muted:!1,error:e instanceof Error?e.message:String(e)}}))})}select(e){let t=et.store.state,n=L.store.state;this.releaseAudioPending||=(this.ownedSessionId!==null||this.handoffActive)&&n===null&&t===void 0,this.ownedSessionId=n,this.handoffActive=t!==void 0;let r=++this.selectionGeneration;e??=(t?.phase===`rebinding`?t.targetSessionId:void 0)??t?.sourceSessionId??null,e!==this.boundSessionId&&t===void 0&&this.client?.endRealtime();let i=async()=>{this.closed||r!==this.selectionGeneration||(this.releaseAudioPending&&=(await this.detach(),await this.device.close(),!1),!(this.closed||r!==this.selectionGeneration)&&(e===null?await this.detach():await this.attach(e,r)))};this.operation=this.operation.then(i,i).then(()=>void 0,()=>void 0)}async attach(e,t,n=!1,r){if(this.client!==void 0&&this.boundSessionId===e||(await this.detach(),this.closed||t!==this.selectionGeneration))return;let i;i=new cn(this.clientId,`connection-${crypto.randomUUID()}`,new Vr(e,n,r),this.device,(t,n)=>{this.client===i&&this.boundSessionId===e&&(t===`disconnected`?R.store.state?.sessionId===e&&R.reset():(R.update(n=>n?.sessionId===null&&n.realtime!==void 0&&n.realtime.connection!==`failed`?n:n?.sessionId===e?{...n,phase:t}:{sessionId:e,phase:t}),t===`conflict`?this.reportOwnership(e,n,r):t===`connected`&&R.update(t=>t?.sessionId===e?{...t,ownership:void 0,ownershipConflict:void 0,actions:void 0}:t)))},t=>{if(this.client!==i||this.boundSessionId!==e)return;let n=R.store.state;n?.sessionId===e&&R.update(()=>({...n,...t===void 0?{}:{realtime:t},...t===void 0?{realtime:void 0,realtimeOutputInterrupted:void 0}:{}}))},e=>new Rt(e,vn)),this.client=i,this.boundSessionId=e,z.store.state?.sessionId!==null&&z.update(()=>({sessionId:e,mute:e=>i.muteRealtime(e),interrupt:()=>{i.interruptRealtime();let t=R.store.state;t?.sessionId===e&&R.update(()=>({...t,realtimeOutputInterrupted:!0}))},end:()=>i.endRealtime()})),i.start()}reportOwnership(e,t,n){let r=t instanceof Error&&`conflict`in t?t.conflict:void 0;if(r?.code!==`VOICE_OWNERSHIP_CONFLICT`)return;let i=ke({header:_()}),a=i.status===`ok`&&i.metadata.deviceId===r.owner.deviceId;R.update(t=>({...t?.sessionId===e?t:{sessionId:e,phase:`conflict`},ownership:{kind:n===void 0?a?`standby`:`conflict`:`stale`,ownerName:r.owner.deviceName,deviceName:i.status===`ok`?i.metadata.deviceName:void 0},ownershipConflict:r,actions:{takeOver:()=>{this.retryOwnership(e,r.owner.generation)},retry:()=>{this.retryOwnership(e)}}}))}async retryOwnership(e,t){try{if(e===null){let e=this.globalClient;this.globalClient=void 0,await e?.stop(!1),this.startGlobalClient(!0,t)}else await this.prepareSessionActivation(e,t)}catch(n){this.reportOwnership(e,n,t)}}async detach(){let e=this.client,t=this.boundSessionId;this.client=void 0,this.boundSessionId=void 0,t!==void 0&&R.store.state?.sessionId===t&&R.reset(),t!==void 0&&z.store.state?.sessionId===t&&z.reset(),await e?.stop(!1)}};function Ur(e){let t=tt.store.state;return t===void 0&&(t=new Hr,tt.update(()=>t)),e.mount?.scope===`session`&&t.focus(e.mount.sessionId),e.openSession&&(t.openSession=t=>e.openSession?.(t)),()=>void 0}var Wr=u(Ur),Gr={id:`voice`,label:`voice`,detail:`Speak requests and hear Po narrate its work. Available voice features depend on the session host.`,order:60,groups:[{id:`start`,label:`New sessions start with`,detail:`Press v e in a session to start voice.`},{id:`live`,label:`Live conversation`,detail:`Live handles the talking. Po still does the work in your session.`,signInProvider:`po-chatgpt`},{id:`daily`,label:`Daily work`,detail:`Listens with the session host’s transcriber. Dictation from the composer uses the same transcriber.`},{id:`narration`,label:`Narration`,detail:`How daily work corrects what it heard and speaks back.`}],fields:[{id:`mode`,localOnly:!0,label:`New sessions start with`,kind:`select`,keyPath:[`voice`,`mode`],group:`start`,presentation:`cards`,defaultValue:`legacy`,options:[{value:`live`,label:`Live conversation`,detail:`Experimental. Back-and-forth talk that answers as you speak. Best for thinking out loud with Po.`},{value:`legacy`,label:`Daily work`,detail:`Say a request, Po transcribes it and narrates as it works. Best while Po is busy.`}]},{id:`live-voice`,localOnly:!0,label:`Voice`,kind:`select`,keyPath:[`voice`,`live`,`voice`],group:`live`,placeholder:`Default (cove)`,options:[`juniper`,`maple`,`spruce`,`ember`,`vale`,`breeze`,`arbor`,`sol`,`cove`,`aube`,`bubbie`,`haetsal`,`hanul`,`himari`,`leher`,`miko`,`neer`,`porto`,`rindo`,`rio`,`rivage`,`selva`,`sonna`,`tinta`,`viola`].map(e=>({value:e,label:e}))},{id:`live-model`,localOnly:!0,label:`Model`,kind:`text`,keyPath:[`voice`,`live`,`model`],group:`live`,placeholder:`gpt-live-1-codex`},{id:`engine`,localOnly:!0,label:`Transcriber`,kind:`select`,keyPath:[`voice`,`engine`],group:`daily`,detail:`Auto uses the first one it finds.`,options:[`auto`,`whisper-cpp`,`openai-whisper`,`mlx-whisper`].map(e=>({value:e,label:e}))},{id:`language`,label:`Language`,kind:`text`,keyPath:[`voice`,`language`],group:`daily`,placeholder:`en`},...[`whisper-cpp`,`openai-whisper`,`mlx-whisper`].flatMap(e=>[{id:`${e}-binary`,localOnly:!0,label:`${e} executable`,kind:`text`,keyPath:[`voice`,`adapters`,e,`binary`],group:`daily`},{id:`${e}-model`,localOnly:!0,label:`${e} model`,kind:`text`,keyPath:[`voice`,`adapters`,e,`model`,e===`whisper-cpp`?`path`:`id`],group:`daily`}]),{id:`correction-model`,label:`Correction and narration model`,kind:`select`,optionsFrom:`models`,keyPath:[`voice`,`autoCapture`,`model`],group:`narration`},{id:`endpoint`,label:`Silence before sending (ms)`,kind:`number`,keyPath:[`voice`,`autoCapture`,`utteranceIdleMs`],group:`daily`},{id:`transcription-timeout`,label:`Transcription timeout (ms)`,kind:`number`,keyPath:[`voice`,`autoCapture`,`transcriptionTimeoutMs`],group:`daily`},{id:`narration-engine`,localOnly:!0,label:`Narration engine`,kind:`select`,keyPath:[`voice`,`autoCapture`,`tts`,`engine`],group:`narration`,options:[{value:`macos-say`,label:`macOS say`}]},{id:`narration-voice`,localOnly:!0,label:`Narration voice`,kind:`text`,keyPath:[`voice`,`autoCapture`,`tts`,`voice`],group:`narration`},{id:`narration-rate`,localOnly:!0,label:`Narration rate`,kind:`number`,keyPath:[`voice`,`autoCapture`,`tts`,`rate`],group:`narration`}]},Kr=n({...Gr,icon:ye}),qr=n({...Gr,icon:ye}),Jr=T({name:`voice`,keys:`v e`,statusKey:`po-voice`,activeSource:rt,hideWhenEmpty:!0,marksBackgroundWork:!1,placement:`bottom`,order:60}),Yr=i(at),Xr=i(ot),Zr=ue({data:it}),Qr=ue({slot:`activity.voice`,id:`voice`,component:At}),$r=1e3,ei=100,ti=1e4,ni=3e3,ri=.01,ii=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`],ai=class{startedAt;lastSpeechAt;get speechDetected(){return this.lastSpeechAt!==void 0}observe(e,t){this.startedAt??=t;let n=0;for(let t of e)n+=t*t;if((e.length===0?0:Math.sqrt(n/e.length))>=ri)return this.lastSpeechAt=t,!1;let r=this.lastSpeechAt??this.startedAt,i=this.speechDetected?ni:ti;return t-r>=i}};function oi(e,t){let n=globalThis.AudioContext;if(n===void 0)return()=>void 0;let r,i,a;try{r=new n,i=r.createMediaStreamSource(e);let o=r.createAnalyser();o.fftSize=2048,o.smoothingTimeConstant=.2,i.connect(o);let s=new Float32Array(o.fftSize),c=new ai;a=setInterval(()=>{o.getFloatTimeDomainData(s),c.observe(s,Date.now())&&t(c.speechDetected)},ei),r.resume().catch(()=>void 0)}catch{return i?.disconnect(),r?.close().catch(()=>void 0),()=>void 0}return()=>{a!==void 0&&clearInterval(a),i?.disconnect(),r?.close().catch(()=>void 0)}}function si(){let e=globalThis,t=e.MediaRecorder,n=e.navigator?.mediaDevices;if(t===void 0||n===void 0)throw Error(`This browser cannot record microphone audio.`);return{getUserMedia:async()=>await n.getUserMedia(F),createRecorder:(e,n)=>new t(e,n),isTypeSupported:e=>t.isTypeSupported(e),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),now:()=>Date.now(),watchSilence:oi}}async function ci(e){e??=si();let t=ii.find(t=>e.isTypeSupported(t)),n=await e.getUserMedia(),r;try{r=e.createRecorder(n,t===void 0?void 0:{mimeType:t})}catch(e){for(let e of n.getTracks())e.stop();throw e}let i=[],a=0,o,s=!1,c=!1,l=!1,u=0,d=()=>void 0,f=()=>void 0,p=()=>void 0,m=new Promise((e,t)=>{f=e,p=t}),h=()=>{e.clearTimer(y),d(),r.ondataavailable=null,r.onerror=null,r.onstop=null;for(let e of n.getTracks())e.onended=null,e.stop()},g=(t,n)=>{s||(s=!0,h(),n===void 0?f(c||t===void 0?void 0:{audio:t,durationMs:Math.min(ut,Math.max(0,Math.round(e.now()-u)))}):p(n))},_=()=>{let e=r.mimeType||i.find(e=>e.type.length>0)?.type||``;return new Blob(i,{type:e})},v=()=>{if(!(s||l)&&r.state!==`inactive`){l=!0;try{r.stop()}catch(e){g(void 0,e instanceof Error?e:Error(`Browser audio recording failed.`))}}},y=e.setTimer(v,ut);for(let e of n.getTracks())e.onended=()=>g(void 0,Error(`The selected microphone was disconnected.`));r.ondataavailable=e=>{if(s||c||o!==void 0||e.data.size===0)return;let t=a+e.data.size;t>4194304?(o=Error(`The recording exceeds the 4 MiB transcription limit.`),v()):(a=t,i.push(e.data))},r.onerror=e=>g(void 0,o??e.error??Error(`Browser audio recording failed.`)),r.onstop=()=>g(o===void 0?_():void 0,o);try{u=e.now(),r.start($r);let t=e.watchSilence?.(n,e=>{e||(c=!0),v()});t!==void 0&&(d=t,s&&d())}catch(e){g(void 0,e instanceof Error?e:Error(`Browser audio recording failed.`)),await m}return{result:m,stop:v,cancel:()=>{c=!0,v()}}}function li(e){if(typeof e!=`object`||!e||!(`transcript`in e))return;let t=e.transcript;return typeof t==`string`?t:void 0}async function ui(e,t,n,r){if(e.size===0)throw Error(`The recording is empty.`);if(e.size>4194304)throw Error(`The recording exceeds the 4 MiB transcription limit.`);if(!Number.isSafeInteger(n)||n<0||n>3e5)throw Error(`The recording duration is invalid.`);let i=await H.session(t).manualTranscribe({headers:{"content-type":e.type,[lt]:String(n)},body:e,...r===void 0?{}:{signal:r}}),a=li(i.data);if(!i.ok)throw Error(i.error===``?`Voice transcription failed with status ${String(i.status)}.`:i.error);if(a===void 0)throw Error(`Voice transcription returned an invalid response.`);return a}var di={start:ci,transcribe:async(e,t,n,r)=>await ui(e,t,n,r)},fi=class{append;changed;dependencies;state={phase:`idle`};recording;transcription;generation=0;constructor(e,t,n=di){this.append=e,this.changed=t,this.dependencies=n}snapshot(){return this.state}setAppend(e){this.append=e}reset(){this.invalidate(),this.publish({phase:`idle`})}dispose(){this.invalidate(),this.state={phase:`idle`}}async toggle(e){if(e===null||this.state.phase===`starting`||this.state.phase===`transcribing`)return;if(this.state.phase===`recording`){this.publish({phase:`transcribing`}),this.recording?.stop();return}let t=this.append,n=++this.generation;this.publish({phase:`starting`});try{let r=await this.dependencies.start();if(this.generation!==n){r.cancel();return}this.recording=r,this.publish({phase:`recording`}),this.finish(r,n,e,t)}catch(e){if(this.generation!==n)return;this.publish({phase:`idle`,error:e instanceof Error?e.message:`Voice recording failed.`})}}async finish(e,t,n,r){let i;try{let a=await e.result;if(this.generation!==t)return;if(a===void 0){this.recording=void 0,this.publish({phase:`idle`});return}this.recording===e&&(this.recording=void 0),this.publish({phase:`transcribing`}),i=new AbortController,this.transcription=i;let o=await this.dependencies.transcribe(a.audio,n,a.durationMs,i.signal);if(this.generation!==t)return;r(o),this.publish({phase:`idle`})}catch(n){if(this.generation!==t)return;this.recording===e&&(this.recording=void 0),this.publish({phase:`idle`,error:n instanceof Error?n.message:`Voice recording failed.`})}finally{i!==void 0&&this.transcription===i&&(this.transcription=void 0)}}invalidate(){this.generation+=1,this.recording?.cancel(),this.recording=void 0,this.transcription?.abort(),this.transcription=void 0}publish(e){this.state=e,this.changed()}},pi=`manual voice is unavailable while autonomous voice is active`;function mi({error:e,onDismiss:t,children:n}){return p(g,{open:e!==void 0,onOpenChange:e=>{e||t()},children:[l(y,{asChild:!0,children:n}),p(c,{side:`top`,align:`end`,sideOffset:8,collisionPadding:12,role:`alert`,"data-testid":`composer-voice-error`,onOpenAutoFocus:e=>e.preventDefault(),className:`w-64 flex-row items-start gap-2 border-po-edge-red bg-po-tint-red p-2.5 text-sm leading-relaxed text-po-red`,children:[l(fe,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),l(`span`,{className:`min-w-0 flex-1 break-words`,children:e}),l(S,{"aria-label":`dismiss`,className:`shrink-0 rounded-sm p-0.5 hover:bg-po-tint-red`,children:l(x,{"aria-hidden":!0,className:`size-3.5`})})]})]})}function hi({sessionId:t,appendComposerDraft:n,statuses:r,registeredModes:i}){let a=w(L.store,e=>e),o=w(R.store),c=xt(r[`po-voice`]),[u,d]=M({phase:`idle`}),p=f(void 0);p.current??=new fi(n,()=>{d(p.current?.snapshot()??{phase:`idle`})});let m=u.phase,h=u.error,g=o?.sessionId===null&&o.realtime!==void 0&&o.realtime.connection!==`closed`,_=c.mode===`auto`||c.mode===`live`||a!==null||g;s(()=>{let e=p.current;return()=>e?.dispose()},[]),s(()=>{p.current?.setAppend(n)},[n]),s(()=>{p.current?.reset()},[t,_]);let v=()=>{_||p.current?.toggle(t)},y=!_&&m===`recording`,b=_?pi:h??(y?`stop voice recording and fill the prompt`:m===`transcribing`?`transcribing voice recording`:m===`starting`?`starting voice recording`:`start voice recording`),x=_?`blocked`:m,S=h&&!_?`text-po-red`:`text-po-dim`;return i?.includes(`voice-auto`)?l(mi,{error:_?void 0:h,onDismiss:()=>p.current?.reset(),children:l(e,{variant:y?`danger-outline`:`ghost`,size:`icon-md`,"data-testid":`composer-voice-action`,"data-voice-mode":_?`auto`:y?`manual`:`off`,"data-voice-phase":x,"aria-label":b,title:b,disabled:t===null||_||m===`starting`||m===`transcribing`,onClick:v,className:`shrink-0 ${S}`,children:y?l(C,{className:`size-3 fill-current`}):m===`starting`||m===`transcribing`?l(ae,{className:`size-4 animate-spin`}):l(h&&!_?fe:ye,{className:`size-4`})})}):null}var gi=ue({slot:`composer-actions`,id:`voice`,component:hi});function _i(e){let t=t=>e[t]?.label||`Microphone`;return e.map((n,r)=>e.some((e,n)=>n!==r&&t(n)===t(r))?`${t(r)} · ${n.deviceId.slice(0,6)}`:t(r))}function vi(){let{inputs:t,choice:n}=w(G.store,e=>e),[i,a]=M(0);if(n===void 0)return null;let s=_i(t),c=i<s.length?i:0,u=e=>{let r=t[s.indexOf(e)];r!==void 0&&n(r.deviceId,!0)};return l(O,{open:!0,onOpenChange:e=>{e||n(null,!1)},children:p(d,{width:`sm`,"data-testid":`voice-microphone-dialog`,"aria-describedby":void 0,onKeyDown:e=>he(e,{options:s,cursor:c,onCursorChange:a,onSelect:u}),children:[l(te,{children:l(re,{children:`choose a microphone`})}),p(o,{children:[l(me,{children:`autonomous voice found more than one input. this browser remembers the one you pick.`}),l(r,{options:s,cursor:c,onCursorChange:a,onSelect:u,testIdPrefix:`voice-microphone-option`}),p(ne,{className:`flex-col items-stretch`,children:[p(`span`,{className:`w-full text-sm text-po-dim`,children:[ve(s.length),` · esc uses the browser default once`]}),l(e,{variant:`outline`,size:`md`,"data-testid":`voice-microphone-default`,onClick:()=>n(null,!0),children:`always use browser default`})]})]})]})})}var yi=ue({slot:`overlay`,id:`voice`,component:vi}),bi=v({id:`voice.toggle`,path:[{key:`v`,label:`voice`,detail:`autonomous voice capture`},{key:`e`,label:`toggle`,detail:`start or stop autonomous capture`}],command:`mode voice-auto`}),xi=u(Ur),Si=b({name:`voice`,modeId:`voice-auto`,keys:`v e`,icon:ye,statusKey:`po-voice`,order:60}),Ci=`describe_voice_tools`,wi=`use_voice_tools`,Ti=`narrate`,Ei=`transfer_voice`,Di=6,Oi=8,ki=72,Ai={tone:`error`,glyph:`✗`,label:`failed`},ji={playing:{tone:`warning`,glyph:`◐`,label:`playing`},completed:{tone:`success`,glyph:`✓`,label:`completed`},interrupted:{tone:`warning`,glyph:`⊘`,label:`interrupted`},superseded:{tone:`dim`,glyph:`○`,label:`superseded`},failed:Ai,rejected:{tone:`error`,glyph:`✗`,label:`rejected`},cancelled:{tone:`warning`,glyph:`⊘`,label:`cancelled`},stopped:{tone:`warning`,glyph:`■`,label:`stopped`},not_executed:{tone:`dim`,glyph:`○`,label:`not executed`},preflight_failed:{tone:`error`,glyph:`✗`,label:`preflight failed`}};function Y(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function X(e){return e!==void 0}function Mi(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e<=31||e===127?` `:n}return t.replace(/\s+/gu,` `).trim()}function Z(e,t){let n=e?.[t];return typeof n==`string`&&Mi(n)||void 0}function Ni(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Pi(e){return e?e.content.flatMap(e=>{let t=Y(e);return t?.type===`text`&&typeof t.text==`string`?[t.text]:[]}):[]}function Fi(e){if(e)try{return Y(JSON.parse(e))}catch{return}}function Ii(e){return Y(e?.details)??Fi(Pi(e)[0])}function Li(e,t,n=`${t}s`){return e===1?t:n}function Q(e,t,n={}){return{text:e,tone:t,...n}}function Ri(e){let t=e.names;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function zi(e){let t=e.calls;return Array.isArray(t)?t.map(Y).filter(X):[]}function Bi(e,t){if(e===`narrate`){let e=typeof t.text==`string`?Mi(t.text):``,n=e.length>ki?`${e.slice(0,69)}…`:e;return{action:`narrate`,...n?{detail:n}:{},detailIsName:!1}}if(e===`transfer_voice`){let e=Ni(t,`target`);return{glyph:`↪`,action:`hand off`,...e===void 0?{}:{detail:`target ${e}`},detailIsName:!1}}if(e===`describe_voice_tools`){let e=Ri(t);return e.length===1?{glyph:`☰`,action:`discover`,detail:e[0],detailIsName:!0}:e.length>1?{glyph:`☰`,action:`discover`,detail:`· ${e.length} capabilities`,detailIsName:!1}:{glyph:`☰`,action:`discover`,detailIsName:!1}}let n=zi(t);if(n.length===1){let e=Z(n[0],`name`);return{glyph:`▶`,action:`run`,...e?{detail:e}:{},detailIsName:e!==void 0}}return n.length>1?{glyph:`▶`,action:`run`,detail:`· ${n.length} capabilities`,detailIsName:!1}:{glyph:`▶`,action:`run`,detailIsName:!1}}function Vi(e){let t=e.enum;if(Array.isArray(t)){let e=t.filter(e=>[`string`,`number`,`boolean`].includes(typeof e));if(e.length>0)return e.join(` | `)}let n=e.const;if([`string`,`number`,`boolean`].includes(typeof n))return String(n);let r=e.type;if(typeof r==`string`)return r;if(Array.isArray(r))return r.filter(e=>typeof e==`string`).join(` | `);if(Array.isArray(e.anyOf)){let t=e.anyOf.map(Y).filter(X).map(Vi).filter(Boolean);if(t.length>0)return t.join(` | `)}return`value`}function Hi(e){let t=Y(e),n=Y(t?.properties);if(!t||!n)return;let r=new Set(Array.isArray(t.required)?t.required.filter(e=>typeof e==`string`):[]),i=Object.entries(n).map(([e,t])=>{let n=Y(t),i=n?Vi(n):`value`;return`${e}${r.has(e)?``:`?`}: ${i}`});return i.length>0?i.join(`, `):`{}`}function Ui(e,t){let n=e.enabled===!0,r=Z(e,`name`)??`capability`,i=Z(e,`label`)??r,a=[Q(`${n?`●`:`○`} ${i} · ${r}${n?``:` · disabled`}`,n?`text`:`dim`)];if(!t)return a;let o=Z(e,`description`),s=Hi(e.inputSchema);return o&&a.push(Q(o,`muted`,{indent:!0})),s&&a.push(Q(`input ${s}`,`dim`,{indent:!0})),a}function Wi(e,t){let n=Array.isArray(e.tools)?e.tools.map(Y).filter(X):[],r=Array.isArray(e.conflicts)?e.conflicts.map(Y).filter(X):[],i=Array.isArray(e.unknownNames)?e.unknownNames.filter(e=>typeof e==`string`):[],a=Ni(e,`catalogRevision`),o=`${n.length} voice ${Li(n.length,`capability`,`capabilities`)}${a===void 0?``:` · catalog rev ${a}`}`,s=t?n:n.slice(0,Di),c=[Q(o,`muted`),...s.flatMap(e=>Ui(e,t))],l=n.length-s.length;l>0&&c.push(Q(`… ${l} more`,`dim`)),n.length===0&&c.push(Q(`No voice capabilities are currently registered.`,`dim`));for(let e of r){let t=Z(e,`name`)??`capability`,n=Z(e,`message`)??`Conflicting registrations.`;c.push(Q(`! ${t} · ${n}`,`warning`))}return i.length>0&&c.push(Q(`? Unknown: ${i.join(`, `)}`,`warning`)),c}function Gi(e){if(typeof e==`string`)return Mi(e);if(typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`)return String(e);if(e===null)return`null`;if(Array.isArray(e)){let t=e.map(Gi);return t.every(e=>e!==void 0)?t.join(`, `)||`none`:void 0}}function Ki(e){let t=Gi(e);if(t!==void 0)return[Q(t,`text`,{indent:!0})];let n=Y(e);return n?Object.entries(n).flatMap(([e,t])=>{let n=Gi(t);return n===void 0?[]:[Q(`${e} ${n}`,`text`,{indent:!0})]}):[]}function qi(e){return Z(Y(e.error),`message`)}function Ji(e,t){let n=Z(e,`name`)??`capability`,r=Z(e,`status`)??`failed`,i=ji[r]??Ai,a=qi(e),o=[Q(`${i.glyph} ${n} · ${i.label}${a?` · ${a}`:``}`,i.tone)];return r===`completed`&&(t||e.result!==void 0)&&o.push(...Ki(e.result)),o}function Yi(e,t){let n=Array.isArray(e.results)?e.results.map(Y).filter(X):[],r=Array.isArray(e.errors)?e.errors.map(Y).filter(X):[],i=ji[Z(e,`status`)??`failed`]??Ai,a=`${i.glyph} Voice batch ${i.label} · ${n.length} ${Li(n.length,`call`)}`,o=t?n:n.slice(0,Oi),s=[Q(a,i.tone,{bold:!0}),...o.flatMap(e=>Ji(e,t))],c=n.length-o.length;c>0&&s.push(Q(`… ${c} more`,`dim`));for(let e of r){let t=Z(e,`message`);t&&!n.some(e=>qi(e)===t)&&s.push(Q(`✗ ${t}`,`error`))}return s}function Xi(e){let t=Y(e.error);if(t)return[Q(`✗ ${Z(t,`message`)??`Voice capability failed.`}${t.retryable===!0?` · retryable`:``}`,`error`)]}function Zi(e,t){let n=Mi(Pi(e)[0]??(t.isPartial?`running`:`No result details.`)),r=t.isPartial?`◐`:t.isError?`✗`:`✓`,i=t.isPartial?`warning`:t.isError?`error`:`muted`;return[Q(`${r} ${n}`,i)]}function Qi(e,t){let n=Ii(e),r=n?Xi(n):void 0;if(r)return r;let i=Z(n,`outcome`)??(t.isPartial?`playing`:void 0);if(!i)return Zi(e,t);let a=ji[i]??Ai;return[Q(`${a.glyph} Narration ${a.label}`,a.tone)]}function $i(e){let t=Z(e,`state`),n=Z(e,`mode`);if(!t||!n||typeof e.muted!=`boolean`)return;let r=Z(e,`manual`),i=Z(e,`error`);return{state:t,phase:t===`active`?`active`:t===`starting`||t===`stopping`?`pending`:`idle`,mode:n,muted:e.muted,...r?{manual:r}:{},...i?{error:i}:{}}}function ea(e){return Object.entries(e).flatMap(([e,t])=>{let n=Gi(t);if(n!==void 0)return[{key:e,value:n||`empty`}];if(Array.isArray(t))return[{key:e,value:`${t.length} ${Li(t.length,`item`)}`}];let r=Y(t);if(!r)return[];let i=Object.keys(r).length;return[{key:e,value:`${i} ${Li(i,`field`)}`}]})}function ta(e,t,n){let r=e===`narrate`?void 0:Ii(t);if(!(!r||Y(r.error)!==void 0||e===`describe_voice_tools`&&Array.isArray(r.tools)||e===`use_voice_tools`&&Array.isArray(r.results))){let e=$i(r);return e?{kind:`status`,status:e}:{kind:`fields`,fields:ea(r)}}return{kind:`lines`,lines:ia(e,t,n)}}function na(e){return typeof e.text==`string`?e.text.normalize(`NFKC`).replace(/\s+/gu,` `).trim():``}function ra(e){return Z(Y(Ii(e)?.error),`message`)||Mi(Pi(e)[0]??``)}function ia(e,t,n){if(e===`narrate`)return Qi(t,n);let r=Ii(t);return(r?Xi(r):void 0)||(e===`describe_voice_tools`&&r&&Array.isArray(r.tools)?Wi(r,n.expanded):e===`use_voice_tools`&&r&&Array.isArray(r.results)?Yi(r,n.expanded):Zi(t,n))}function aa({toolName:e,args:t,result:n,running:r,isError:i}){if(e===`narrate`){let e=na(t);return p(`div`,{role:`group`,"aria-label":`narration`,"data-testid":`narration-message`,"data-narration-state":r?`playing`:i?`failed`:`complete`,className:`flex min-w-0 items-start gap-2 text-base text-po-text`,children:[l(le,{"aria-hidden":`true`,className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-po-magenta`}),l(`p`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:e||`Narration unavailable.`})]})}let o=Bi(e,t),s=ia(e,n,{expanded:!1,isError:i,isPartial:r}),c=ia(e,n,{expanded:!0,isError:i,isPartial:r}),u=ta(e,n,{expanded:!1,isError:i,isPartial:r}),d=i?ra(n):``;return l(de,{tone:h({running:r,isError:i}),expandable:!i&&c.length>s.length,children:({expanded:t})=>p(a,{children:[l(se,{title:e,children:p(`span`,{"data-testid":`tool-call-${e}`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[p(`span`,{className:`shrink-0 font-semibold text-po-hi`,children:[o.glyph,` `,o.action]}),o.detail?l(`span`,{className:`min-w-0 truncate ${o.detailIsName?`text-po-blue`:`text-po-dim`}`,children:o.detail}):null]})}),i?d.length>0?l(ce,{"data-testid":`tool-result-${e}`,children:l(`p`,{className:`whitespace-pre-wrap break-words text-po-red`,children:d})}):null:l(ce,{"data-testid":`tool-result-${e}`,children:r&&n===null?l(ie,{tone:`running`,children:`running`}):u.kind===`status`?l(sa,{status:u.status}):u.kind===`fields`?l(ca,{fields:u.fields}):l(ge,{lines:t?c:s})})]})})}var oa={active:`green`,pending:`yellow`,idle:`neutral`};function sa({status:e}){return p(`div`,{className:`flex flex-col gap-2`,children:[p(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[l(A,{tone:oa[e.phase],children:`voice ${e.state}`}),l(A,{tone:`blue`,children:`mode ${e.mode}`}),l(A,{tone:e.muted?`yellow`:`neutral`,children:e.muted?`mic muted`:`mic on`}),e.manual===void 0?null:l(A,{children:`dictation ${e.manual}`})]}),e.error===void 0?null:l(`p`,{className:`break-words text-po-red`,children:e.error})]})}function ca({fields:e}){return e.length===0?l(`p`,{className:`text-po-faint`,children:`No result details.`}):l(`dl`,{className:`grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-4 gap-y-0.5`,children:e.map(e=>p(`div`,{className:`contents`,children:[l(`dt`,{className:`truncate text-po-dim`,children:e.key}),l(`dd`,{className:`break-words text-po-text`,children:e.value})]},e.key))})}var la=D({tools:[Ti],timelinePresentation:`message`,message:aa}),ua=D({tools:[Ci,wi,Ei],message:aa}),$=(e,t)=>t===void 0?void 0:{...e,...t},da=pe({id:`voice`,packageName:`@agimon-ai/po-voice`,host:{get fills(){return[$({slot:`activity`,id:`voice`},Mt)]},get settingsSections(){return[$({id:`voice`},Kr)]},get start(){return Wr}},workspace:{get settingsSections(){return[$({id:`voice`},qr)]}},session:{get activityGroups(){return[$({name:`voice`},Jr)]},get channels(){return[$({channel:`voice_media_wake`},Yr),$({channel:`voice_ownership`},Xr)]},get fills(){return[$({slot:`approval.voice-hint`,id:`approval-voice-hint`},Zr),$({slot:`activity.voice`,id:`voice`},Qr),$({slot:`composer-actions`,id:`voice`},gi),$({slot:`overlay`,id:`voice`},yi)]},get leaderBindings(){return[$({id:`voice.toggle`},bi)]},get modes(){return[$({name:`voice`},Si)]},get start(){return xi},get toolRenderers(){return[$({tools:[`narrate`]},la),$({tools:[`voice`]},ua)]}}});export{da as webPlugin};
@@ -1 +1 @@
1
- import{Ft as e,It as t,Lt as n,Mi as r,Oi as i,Wa as a,_n as o,gn as s,hn as c,mn as l,qa as u}from"../chunks/po-web-runtime-CQ9hLtG-.js";var d=[`cached`,`indexed`,`live`],f=2048;function p(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[]}function m(e){return typeof e==`string`?e:``}var h=/^[a-z][a-z\d+.-]*:/i;function g(e){if(!h.test(e))return!1;try{return new URL(e),!0}catch{return!1}}function _(e){return g(e)?e:``}function v(e){let t=p(e).map(e=>m(e.q));if(t.length===0)return;let n=t[0];return{kind:`search`,detail:t.length>1&&n?`${n} ...`:n}}function y(e){let t=v(e.search_query)??v(e.image_query);if(t)return t;let n=_(m(p(e.open)[0]?.ref_id));if(n)return{kind:`open`,detail:n};let r=p(e.find)[0];if(r){let e=m(r.pattern),t=_(m(r.ref_id));return{kind:`find`,detail:e&&t?`'${e}' in ${t}`:e?`'${e}'`:t,pattern:!!e}}return{kind:`other`}}function b(e,t){if(e.kind===`open`)return`${t?`Opened`:`Opening`} ${e.detail}`;if(e.kind===`find`){let n=e.pattern?t?`Searched for`:`Searching for`:t?`Searched page`:`Searching page`;return e.detail?`${n} ${e.detail}`:n}let n=e.kind===`search`?e.detail:``;return n?`${t?`Searched the web`:`Searching the web`} for ${n}`:t?`Searched the web`:e.kind===`other`?`Browsing the web`:`Searching the web`}function x(e){return typeof e!=`object`||!e?[]:p(e.sources).flatMap(e=>{let t=m(e.url);if(t.length>f||!g(t))return[];let n=new URL(t);if(n.protocol!==`https:`&&n.protocol!==`http:`)return[];let r=m(e.title).trim();return[{url:n.href,label:r||n.hostname,domain:n.hostname.replace(/^www\./,``),title:r}]})}function S(e){return e.kind===`other`?``:e.detail.replace(/https?:\/\//g,``)}function C({args:e,result:t,running:n}){let r=t?.details,i=typeof r==`object`&&r?r:{},a=y(e);return{summary:b(a,!n),subject:S(a),access:d.find(e=>e===i.access),sharedConversation:i.sharedConversation===!0,sources:x(r)}}function w(a){let{result:u,output:d,running:f,isError:p,defaultExpanded:m=!1}=a,h=C(a),g=h.access?`${h.access}${h.sharedConversation?` · with recent conversation`:``}`:``;return t(l,{tone:r({running:f,isError:p}),expandable:!0,defaultExpanded:m,children:({expanded:r})=>n(e,{children:[n(s,{title:`web search`,children:[t(`span`,{"data-testid":`tool-call-web_run`,className:`min-w-0 flex-1 truncate text-po-text`,children:h.summary}),g?t(`span`,{className:`shrink-0 text-po-faint`,children:g}):null]}),r?n(c,{"data-testid":`tool-result-web_run`,className:`flex flex-col gap-2`,children:[f?t(o,{tone:`running`,children:`searching`}):null,p?t(o,{tone:`error`,children:`failed`}):null,!p&&h.sources.length>0?t(`ul`,{"aria-label":`Sources`,className:`flex flex-col gap-1`,children:h.sources.map(e=>t(`li`,{className:`min-w-0 truncate`,children:t(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-po-blue underline decoration-po-blue/50`,children:e.label})},e.url))}):null,i(u,d).map((e,n)=>t(`span`,{className:`whitespace-pre-wrap break-words ${p?`text-po-red`:`text-po-dim`}`,children:e},`${String(n)}-${e}`))]}):null]})})}var T=a({message:w}),E=(e,t)=>t===void 0?void 0:{...e,...t},D=u({id:`web-search`,packageName:`@agimon-ai/po-web-search`,session:{get toolRenderers(){return[E({tools:[`web_run`]},T)]}}});export{D as webPlugin};
1
+ import{Ft as e,It as t,Lt as n,Mi as r,Oi as i,Wa as a,_n as o,gn as s,hn as c,mn as l,qa as u}from"../chunks/po-web-runtime-C0B3uAoC.js";var d=[`cached`,`indexed`,`live`],f=2048;function p(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e):[]}function m(e){return typeof e==`string`?e:``}var h=/^[a-z][a-z\d+.-]*:/i;function g(e){if(!h.test(e))return!1;try{return new URL(e),!0}catch{return!1}}function _(e){return g(e)?e:``}function v(e){let t=p(e).map(e=>m(e.q));if(t.length===0)return;let n=t[0];return{kind:`search`,detail:t.length>1&&n?`${n} ...`:n}}function y(e){let t=v(e.search_query)??v(e.image_query);if(t)return t;let n=_(m(p(e.open)[0]?.ref_id));if(n)return{kind:`open`,detail:n};let r=p(e.find)[0];if(r){let e=m(r.pattern),t=_(m(r.ref_id));return{kind:`find`,detail:e&&t?`'${e}' in ${t}`:e?`'${e}'`:t,pattern:!!e}}return{kind:`other`}}function b(e,t){if(e.kind===`open`)return`${t?`Opened`:`Opening`} ${e.detail}`;if(e.kind===`find`){let n=e.pattern?t?`Searched for`:`Searching for`:t?`Searched page`:`Searching page`;return e.detail?`${n} ${e.detail}`:n}let n=e.kind===`search`?e.detail:``;return n?`${t?`Searched the web`:`Searching the web`} for ${n}`:t?`Searched the web`:e.kind===`other`?`Browsing the web`:`Searching the web`}function x(e){return typeof e!=`object`||!e?[]:p(e.sources).flatMap(e=>{let t=m(e.url);if(t.length>f||!g(t))return[];let n=new URL(t);if(n.protocol!==`https:`&&n.protocol!==`http:`)return[];let r=m(e.title).trim();return[{url:n.href,label:r||n.hostname,domain:n.hostname.replace(/^www\./,``),title:r}]})}function S(e){return e.kind===`other`?``:e.detail.replace(/https?:\/\//g,``)}function C({args:e,result:t,running:n}){let r=t?.details,i=typeof r==`object`&&r?r:{},a=y(e);return{summary:b(a,!n),subject:S(a),access:d.find(e=>e===i.access),sharedConversation:i.sharedConversation===!0,sources:x(r)}}function w(a){let{result:u,output:d,running:f,isError:p,defaultExpanded:m=!1}=a,h=C(a),g=h.access?`${h.access}${h.sharedConversation?` · with recent conversation`:``}`:``;return t(l,{tone:r({running:f,isError:p}),expandable:!0,defaultExpanded:m,children:({expanded:r})=>n(e,{children:[n(s,{title:`web search`,children:[t(`span`,{"data-testid":`tool-call-web_run`,className:`min-w-0 flex-1 truncate text-po-text`,children:h.summary}),g?t(`span`,{className:`shrink-0 text-po-faint`,children:g}):null]}),r?n(c,{"data-testid":`tool-result-web_run`,className:`flex flex-col gap-2`,children:[f?t(o,{tone:`running`,children:`searching`}):null,p?t(o,{tone:`error`,children:`failed`}):null,!p&&h.sources.length>0?t(`ul`,{"aria-label":`Sources`,className:`flex flex-col gap-1`,children:h.sources.map(e=>t(`li`,{className:`min-w-0 truncate`,children:t(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`text-po-blue underline decoration-po-blue/50`,children:e.label})},e.url))}):null,i(u,d).map((e,n)=>t(`span`,{className:`whitespace-pre-wrap break-words ${p?`text-po-red`:`text-po-dim`}`,children:e},`${String(n)}-${e}`))]}):null]})})}var T=a({message:w}),E=(e,t)=>t===void 0?void 0:{...e,...t},D=u({id:`web-search`,packageName:`@agimon-ai/po-web-search`,session:{get toolRenderers(){return[E({tools:[`web_run`]},T)]}}});export{D as webPlugin};