@agimon-ai/po-cloudflare 0.0.2-alpha.48 → 0.0.2-alpha.49

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 (151) hide show
  1. package/dist/assets/assets/{CodeEditorView-C_mYLn6M.js → CodeEditorView-BHaOMRjc.js} +2 -2
  2. package/dist/assets/assets/{abnfDiagram-WEYOIA3C-DefVXGFV.js → abnfDiagram-WEYOIA3C-CDWx0dCZ.js} +2 -2
  3. package/dist/assets/assets/{architecture-WOLXFQ4H-Ftqji05b.js → architecture-WOLXFQ4H-CVl8TlUa.js} +1 -1
  4. package/dist/assets/assets/{architectureDiagram-ZHVYKT53-D8aOrisO.js → architectureDiagram-ZHVYKT53-B-9U5J2m.js} +2 -2
  5. package/dist/assets/assets/{blockDiagram-RJAE7QA3-COb4aakG.js → blockDiagram-RJAE7QA3-DeAmR8GR.js} +2 -2
  6. package/dist/assets/assets/{c4Diagram-XDPPPE54-B0RBwxgS.js → c4Diagram-XDPPPE54-DH-55ik1.js} +2 -2
  7. package/dist/assets/assets/channel-bSjoaDB4.js +2 -0
  8. package/dist/assets/assets/{chunk-2E7WHVMD-xslt64yZ.js → chunk-2E7WHVMD-CtD9IAQe.js} +2 -2
  9. package/dist/assets/assets/{chunk-4EMNKR2T-f3IpLd1J.js → chunk-4EMNKR2T-BlWBPhJT.js} +2 -2
  10. package/dist/assets/assets/{chunk-55XCU76K-D3q6AZAA.js → chunk-55XCU76K-CLbB5lqy.js} +2 -2
  11. package/dist/assets/assets/{chunk-7S6XSTFO-CaV-HpLf.js → chunk-7S6XSTFO-D33yaufg.js} +2 -2
  12. package/dist/assets/assets/{chunk-AQDTSKZB-DbOv8phx.js → chunk-AQDTSKZB-PRYBX44u.js} +2 -2
  13. package/dist/assets/assets/{chunk-DSNLSHJZ-CGoIJL3I.js → chunk-DSNLSHJZ-CyfThOqM.js} +2 -2
  14. package/dist/assets/assets/{chunk-HAGFOTED-K0-xCmev.js → chunk-HAGFOTED-DzN80Tcl.js} +2 -2
  15. package/dist/assets/assets/{chunk-HNE4Q36P-C3I77Xwt.js → chunk-HNE4Q36P-DKoC-RgY.js} +2 -2
  16. package/dist/assets/assets/{chunk-NQOKRVIF-r8UsQoSM.js → chunk-NQOKRVIF-BLXN1l5s.js} +2 -2
  17. package/dist/assets/assets/{chunk-UHW7PFBP-DWmOTjfa.js → chunk-UHW7PFBP-CtkUl02Z.js} +2 -2
  18. package/dist/assets/assets/{chunk-VQ5W62QI-CJV5dZLW.js → chunk-VQ5W62QI-DcSOZjGK.js} +2 -2
  19. package/dist/assets/assets/{chunk-WQQL4CDK-Bfpg87o7.js → chunk-WQQL4CDK-aN1-PJ3t.js} +2 -2
  20. package/dist/assets/assets/chunk-XXDRQBXY-BIzpIYaa.js +2 -0
  21. package/dist/assets/assets/{chunk-YZO67HFG-Cf0ywi0D.js → chunk-YZO67HFG-DhtQKpcb.js} +2 -2
  22. package/dist/assets/assets/{chunk-ZAUX2LTX-iC5Tn6mf.js → chunk-ZAUX2LTX-BKRwwtRo.js} +2 -2
  23. package/dist/assets/assets/{chunk-ZCHMQSOR-DLvEBxTv.js → chunk-ZCHMQSOR-BZT1wRxe.js} +2 -2
  24. package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DjsXLyQa.js → classDiagram-v2-4MYWR3UA-CMWkILSY.js} +2 -2
  25. package/dist/assets/assets/{cose-bilkent-JH36ORCC-Dyl7fgJO.js → cose-bilkent-JH36ORCC-Dar4SYjM.js} +2 -2
  26. package/dist/assets/assets/{cynefin-EF2NZ3EQ-CCTTt4il.js → cynefin-EF2NZ3EQ-Dh1r-XyN.js} +1 -1
  27. package/dist/assets/assets/{cynefinDiagram-WF24UDRP-djxzhWm0.js → cynefinDiagram-WF24UDRP-Dv7zKVsq.js} +2 -2
  28. package/dist/assets/assets/{dagre-NK4GIZVX-CIY5ZJbh.js → dagre-NK4GIZVX-Bf9qZfJX.js} +2 -2
  29. package/dist/assets/assets/{diagram-CBK3MWTC-LaFd7Qht.js → diagram-CBK3MWTC-Ca4NIw3-.js} +2 -2
  30. package/dist/assets/assets/{diagram-I5XIIV2D-Dk5ZMZfF.js → diagram-I5XIIV2D-DR1tHQSH.js} +2 -2
  31. package/dist/assets/assets/{diagram-ODIL2UCW-DN26_SkT.js → diagram-ODIL2UCW-Bja9G_fP.js} +2 -2
  32. package/dist/assets/assets/{diagram-PFBEJUXE-DheR717B.js → diagram-PFBEJUXE-CcKrvx7F.js} +2 -2
  33. package/dist/assets/assets/{diagram-RJA3I4VV-DX5eWt50.js → diagram-RJA3I4VV-ChfUAp5c.js} +2 -2
  34. package/dist/assets/assets/{diagram-TYUNFSNR-CzcDrOnS.js → diagram-TYUNFSNR-Z7EIy_Dd.js} +2 -2
  35. package/dist/assets/assets/{dist-DMawibLu.js → dist-C5b3-Ra2.js} +2 -2
  36. package/dist/assets/assets/{dist-BxOg0kfS.js → dist-C8ca3uHq.js} +2 -2
  37. package/dist/assets/assets/{dist-Baxx78b8.js → dist-CB7zR0aj.js} +2 -2
  38. package/dist/assets/assets/{dist-D-4bVX5R.js → dist-CY2drnbW.js} +2 -2
  39. package/dist/assets/assets/{dist-phEYiQPT.js → dist-CeHA3RMV.js} +2 -2
  40. package/dist/assets/assets/{dist-BguOTt2C.js → dist-CnDVRyzg.js} +2 -2
  41. package/dist/assets/assets/{dist-DgyHiiLg.js → dist-D4ABsHNx.js} +2 -2
  42. package/dist/assets/assets/{dist-Fr_cVur6.js → dist-DkzTnMW6.js} +2 -2
  43. package/dist/assets/assets/{dist-BmdHJeNc.js → dist-pvEcNix9.js} +2 -2
  44. package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-CoM013pL.js → ebnfDiagram-V4P3TTPT-Cj7VJ0V4.js} +2 -2
  45. package/dist/assets/assets/{elk-QONTBCTQ-DmGjc9Hh.js → elk-QONTBCTQ-0md1Ryrf.js} +2 -2
  46. package/dist/assets/assets/{erDiagram-KYQIGQAA-Dz3-bYVx.js → erDiagram-KYQIGQAA-DtERkMAJ.js} +2 -2
  47. package/dist/assets/assets/{eventmodeling-K75KTNOO-CLlxLv2A.js → eventmodeling-K75KTNOO-CSIPK-Eo.js} +1 -1
  48. package/dist/assets/assets/flowDiagram-IUGLLWBU-B9oPI3Eh.js +1 -0
  49. package/dist/assets/assets/{ganttDiagram-R7GPNTJY-DnUTi2Lw.js → ganttDiagram-R7GPNTJY-WODJvYlC.js} +2 -2
  50. package/dist/assets/assets/{gitGraph-VSP46ZUC-BKN2dqtq.js → gitGraph-VSP46ZUC-u62VUFlC.js} +1 -1
  51. package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-DLrrvd0J.js → gitGraphDiagram-PDYL7XHY-nliEw829.js} +2 -2
  52. package/dist/assets/assets/index-BlFg3Cgj.js +200 -0
  53. package/dist/assets/assets/index-CWkfd_A-.css +1 -0
  54. package/dist/assets/assets/{info-OHQRW6UA-BDEgHbYs.js → info-OHQRW6UA-CYikzsdB.js} +1 -1
  55. package/dist/assets/assets/{infoDiagram-MVDRKAX5-C3Nf12JT.js → infoDiagram-MVDRKAX5-CAW8nciZ.js} +2 -2
  56. package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-fbHmqACp.js → ishikawaDiagram-HPEHV2GE-CfEaOuah.js} +2 -2
  57. package/dist/assets/assets/{journeyDiagram-BOSHW7O7-BFGkRISm.js → journeyDiagram-BOSHW7O7-gQ-SjkNw.js} +2 -2
  58. package/dist/assets/assets/{kanban-definition-FNSA4HC5-CT8LXXjC.js → kanban-definition-FNSA4HC5-DMD23QWj.js} +2 -2
  59. package/dist/assets/assets/{line-DNJRN0fU.js → line-BqPW5Rca.js} +2 -2
  60. package/dist/assets/assets/{linear-o7QEED__.js → linear-Gt3NZtDp.js} +2 -2
  61. package/dist/assets/assets/{mermaid-parser.core-CqEUiMwG.js → mermaid-parser.core-jr9WuLKp.js} +4 -4
  62. package/dist/assets/assets/{mermaid.core-UmrHaJ93.js → mermaid.core-nONZH9ES.js} +5 -5
  63. package/dist/assets/assets/{mindmap-definition-6OY57UG3-1CWvf4XD.js → mindmap-definition-6OY57UG3-P0G1aSZ_.js} +2 -2
  64. package/dist/assets/assets/{packet-JDAUHWVQ-DADADHfZ.js → packet-JDAUHWVQ-BRYh19T9.js} +1 -1
  65. package/dist/assets/assets/{pegDiagram-ECIUJNBX-QahCrnnP.js → pegDiagram-ECIUJNBX-DVXvDw5m.js} +2 -2
  66. package/dist/assets/assets/{pie-XZMESJXO-CcVs8yjR.js → pie-XZMESJXO-C4zblXYs.js} +1 -1
  67. package/dist/assets/assets/{pieDiagram-GNMPY74T-IVVcmoj4.js → pieDiagram-GNMPY74T-DQZMSxzU.js} +2 -2
  68. package/dist/assets/assets/{quadrantDiagram-D57K4MC3-CS7f-VeJ.js → quadrantDiagram-D57K4MC3-CoJW9FbN.js} +2 -2
  69. package/dist/assets/assets/{radar-ABXABTNO-imva_GNF.js → radar-ABXABTNO-C1hflkM-.js} +1 -1
  70. package/dist/assets/assets/{railroad-I3PHUGI6-GitT3taK.js → railroad-I3PHUGI6-BWfPWtIx.js} +1 -1
  71. package/dist/assets/assets/{railroad-abnf-LNEFI6M7-DA9a4ok6.js → railroad-abnf-LNEFI6M7-ZD-V0lbr.js} +1 -1
  72. package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-2G9UuZV0.js → railroad-ebnf-DWYD2UWJ-101vSltK.js} +1 -1
  73. package/dist/assets/assets/{railroad-peg-JR7BVNR7-KGkhk5i6.js → railroad-peg-JR7BVNR7-C2qdCoeJ.js} +1 -1
  74. package/dist/assets/assets/{railroadDiagram-Y72NRBL7-DRwAClPI.js → railroadDiagram-Y72NRBL7-CVB1kO7b.js} +2 -2
  75. package/dist/assets/assets/{requirementDiagram-EQYSW5RA-CWcrJ4Kd.js → requirementDiagram-EQYSW5RA-D2U3nwPk.js} +2 -2
  76. package/dist/assets/assets/{sankeyDiagram-SY24JHO5-CkMOBlFF.js → sankeyDiagram-SY24JHO5-CKjkT8B_.js} +2 -2
  77. package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-B10XOG3r.js → sequenceDiagram-BLEHNHQU-CwVqG2fG.js} +2 -2
  78. package/dist/assets/assets/{src-BpxERY-4.js → src-bIf72vcz.js} +2 -2
  79. package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-D50RKXhB.js → stateDiagram-v2-A6IESKWZ-97EIvkg9.js} +2 -2
  80. package/dist/assets/assets/{swimlanes-B3ENRKFQ-DlFQGv2L.js → swimlanes-B3ENRKFQ-D9egyUg3.js} +2 -2
  81. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BkS3IR0c.js +9 -0
  82. package/dist/assets/assets/{timeline-definition-JXYKGLGB-B3Sb86Ee.js → timeline-definition-JXYKGLGB-CbG0LH-D.js} +2 -2
  83. package/dist/assets/assets/{treeView-D4JQ5SDB-C0RfpNmP.js → treeView-D4JQ5SDB-COfpvikT.js} +1 -1
  84. package/dist/assets/assets/{treemap-SAJKECNS-DEYe7AgT.js → treemap-SAJKECNS-CU-jFNpR.js} +1 -1
  85. package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-D--b6tnm.js → usecaseDiagram-WPOLBNNX-BGnYi9SF.js} +2 -2
  86. package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-D1TkV4xk.js → vennDiagram-Q3Y3IDCW-Cb4zd6ET.js} +2 -2
  87. package/dist/assets/assets/{wardley-7MLQ67FV-BW1rHoM4.js → wardley-7MLQ67FV-ULAC2YGd.js} +1 -1
  88. package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-1eGu-wA2.js → wardleyDiagram-IVAIDKWA-Bi-y7zjP.js} +2 -2
  89. package/dist/assets/assets/{webpack-BxGI2QQO.js → webpack-eZcyXM6S.js} +2 -2
  90. package/dist/assets/assets/{xychartDiagram-4URNHDU4-Brc-3D_H.js → xychartDiagram-4URNHDU4-BvTZJqeU.js} +2 -2
  91. package/dist/assets/bundle-asset-policy.json +1 -1
  92. package/dist/assets/index.html +2 -2
  93. package/dist/assets/plugins/assets/base-Bz0oeehA.css +2 -0
  94. package/dist/assets/plugins/chunks/po-web-runtime-oroB3Znq.js +1 -0
  95. package/dist/assets/plugins/compositions.json +1 -1
  96. package/dist/assets/plugins/slots/approval.72ae703a-DFWTk7Ap.js +2 -0
  97. package/dist/assets/plugins/slots/artifacts.77a5ce89--B-D-lue.js +1 -0
  98. package/dist/assets/plugins/slots/author.1c902d5c--QQ4lLeg.js +93 -0
  99. package/dist/assets/plugins/slots/{autocompact.86aeccf4-CcvIN-cI.js → autocompact.f08b6833-BZ-Hd0ei.js} +1 -1
  100. package/dist/assets/plugins/slots/browse.a8452a8d-DekLuc-Z.js +1 -0
  101. package/dist/assets/plugins/slots/{builtin-tools.0a7f0b8e-kbo97l14.js → builtin-tools.abc3edcc-zeBI1cKp.js} +3 -3
  102. package/dist/assets/plugins/slots/codemode.c68822dc-HLrDhndJ.js +11 -0
  103. package/dist/assets/plugins/slots/domain.d3fc60b5-Dwn3GboM.js +1 -0
  104. package/dist/assets/plugins/slots/{edit.c5b0b072-D5UaJjPf.js → edit.2aa43041-CddVpEel.js} +3 -3
  105. package/dist/assets/plugins/slots/files.c1e584ee-DxOpzqm3.js +2 -0
  106. package/dist/assets/plugins/slots/goal.b1d8b03b-C9tmOreI.js +1 -0
  107. package/dist/assets/plugins/slots/grep.b067b8cb-C4OjbSn9.js +1 -0
  108. package/dist/assets/plugins/slots/help.3b3e56cb-CcgpN98Q.js +3 -0
  109. package/dist/assets/plugins/slots/log.24faf8a0-BtnnodkX.js +4 -0
  110. package/dist/assets/plugins/slots/mcp.a6805ffa-DrBGkASK.js +109 -0
  111. package/dist/assets/plugins/slots/plan.19d1704d-C3Tml2Sz.js +3 -0
  112. package/dist/assets/plugins/slots/profile.1b4aeee4-1K7Wt9AD.js +1 -0
  113. package/dist/assets/plugins/slots/{prompts.2c187969-C4F2-Qgt.js → prompts.a5509377-h93o8dcF.js} +2 -2
  114. package/dist/assets/plugins/slots/read.a43eeb4a-DNoCGY1k.js +1 -0
  115. package/dist/assets/plugins/slots/runner.03b699da-DGs8HywA.js +8 -0
  116. package/dist/assets/plugins/slots/sessions.dc7ce5f8-CwbzOt92.js +1 -0
  117. package/dist/assets/plugins/slots/{skill.f5396fde-DjLYO2JJ.js → skill.2b6ba429-6Lp0cyos.js} +2 -2
  118. package/dist/assets/plugins/slots/subagents.9adbe0d5-tX_I8uwl.js +7 -0
  119. package/dist/assets/plugins/slots/vault.593b32bd-dkDWzchJ.js +1 -0
  120. package/dist/assets/plugins/slots/voice.376a066c-Clktk2zw.js +1 -0
  121. package/dist/{server-D9MvODKo.js → server-D0Pm5Cv2.js} +119 -6
  122. package/dist/worker.js +54 -37
  123. package/package.json +39 -39
  124. package/dist/assets/assets/channel-DNl1jI1M.js +0 -2
  125. package/dist/assets/assets/chunk-XXDRQBXY-3eapdwCn.js +0 -2
  126. package/dist/assets/assets/flowDiagram-IUGLLWBU-BFT5SBcS.js +0 -1
  127. package/dist/assets/assets/index-CcUcRF1S.css +0 -1
  128. package/dist/assets/assets/index-DWONOipn.js +0 -200
  129. package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BYHWhExM.js +0 -9
  130. package/dist/assets/plugins/assets/base-LmdY6uBA.css +0 -2
  131. package/dist/assets/plugins/chunks/po-web-runtime-DtS_FP_f.js +0 -1
  132. package/dist/assets/plugins/slots/approval.dd60ec90-m-Ra7Ebe.js +0 -2
  133. package/dist/assets/plugins/slots/artifacts.a078f1a5-DTv8TGH0.js +0 -1
  134. package/dist/assets/plugins/slots/author.497633d0-COLvE24q.js +0 -93
  135. package/dist/assets/plugins/slots/browse.5fcf164c-BgK_ibjS.js +0 -1
  136. package/dist/assets/plugins/slots/codemode.ff16ac06-CXHWhJc8.js +0 -11
  137. package/dist/assets/plugins/slots/domain.3ddea842-CvZmPWdh.js +0 -1
  138. package/dist/assets/plugins/slots/files.8ffcdcc0-COYaael1.js +0 -2
  139. package/dist/assets/plugins/slots/goal.423c7a26-nmfrCrdh.js +0 -1
  140. package/dist/assets/plugins/slots/grep.95f470b3-osJU0D9d.js +0 -1
  141. package/dist/assets/plugins/slots/help.03b9ba99-BZU2hmYF.js +0 -3
  142. package/dist/assets/plugins/slots/log.19bda339-Bi7himlR.js +0 -4
  143. package/dist/assets/plugins/slots/mcp.ffbe405a-aEn779DD.js +0 -109
  144. package/dist/assets/plugins/slots/plan.5eac6563-B8M9sD_u.js +0 -3
  145. package/dist/assets/plugins/slots/profile.176710dd-C38rbDGj.js +0 -1
  146. package/dist/assets/plugins/slots/read.1629d556-Bh5_twoW.js +0 -1
  147. package/dist/assets/plugins/slots/runner.962030e5-B4S52R79.js +0 -8
  148. package/dist/assets/plugins/slots/sessions.fc763f42-Dr4py-zv.js +0 -1
  149. package/dist/assets/plugins/slots/subagents.d815a296-Dew0ZskW.js +0 -7
  150. package/dist/assets/plugins/slots/vault.57fd9047-C0rZL_dc.js +0 -1
  151. package/dist/assets/plugins/slots/voice.b709d05c-DonnEXWO.js +0 -1
@@ -1,3 +0,0 @@
1
- import{A as e,An as t,C as n,Cr as r,D as i,Dn as a,Fr as o,Kt as s,L as c,M as l,Mr as u,On as d,P as f,Qt as p,Rr as m,Sn as h,a as g,b as _,bn as v,d as y,g as b,h as x,hr as S,j as C,kn as w,kr as T,ln as ee,mn as te,mr as ne,n as re,nt as ie,o as E,s as D,wn as ae,wr as oe,xr as se}from"../chunks/po-web-runtime-DtS_FP_f.js";var O=`planning`,k=[`modes`,O],A=`main`,j=`subagents`,M=`inherit the session model`,N=`inherit`,P=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],F={id:O,label:`planning`,detail:`the models plan mode switches to, and where written plans land`,order:30,fields:[{id:`main.model`,label:`main model`,keyPath:[...k,A,`model`],placeholder:M,detail:`model the main agent switches to while plan mode is on.`,models:!0},{id:`main.thinking`,label:`main thinking`,keyPath:[...k,A,`thinking`],placeholder:N,detail:`thinking level appended to the main model while planning.`,options:P},{id:`subagents.model`,label:`subagent model`,keyPath:[...k,j,`model`],placeholder:M,detail:`model forced onto delegated planning subagents.`,models:!0},{id:`subagents.thinking`,label:`subagent thinking`,keyPath:[...k,j,`thinking`],placeholder:N,detail:`thinking level appended to the subagent model.`,options:P},{id:`plansdirectory`,label:`plans directory`,keyPath:[...k,`plansDirectory`],placeholder:`~/.po/plans`,detail:`absolute, repo-relative, or under ~. written plans land here.`}].map(e=>({id:e.id,label:e.label,kind:e.models===!0||e.options!==void 0?`select`:`text`,keyPath:e.keyPath,detail:e.detail,placeholder:e.placeholder,...e.models===!0?{optionsFrom:`models`}:{},...e.options===void 0?{}:{options:e.options.map(e=>({value:e,label:e}))}}))},ce=T({...F,icon:s}),le=T({...F,icon:s}),I=`po-plan-document`,L=[{label:`Exit plan mode and start implementation`,value:`exit`},{label:`Continue planning`,value:`continue`}].map(e=>e.label),ue=` · `,de=/\[[0-9;]*m/gu;function fe(e){if(e===void 0)return;let t=e.replace(de,``).trim();if(t===``)return;let n=t.lastIndexOf(ue);return n===-1?{title:t,stamp:``}:{title:t.slice(0,n).trim(),stamp:t.slice(n+3).trim()}}var pe=S({name:`plan`,keys:`p e`,statusKey:I,marksBackgroundWork:!1,order:25}),R=ne({current:{method:`GET`,path:`/current`,response:void 0},save:{method:`PUT`,path:`/content`,response:void 0}},{scopes:[`session`],basePath:`plans`,transport:(e,t)=>re.fetch(e,t),sessionAddress:m}),me=`The session is unreachable.`,he=`This session has not written a plan yet.`;function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e){return e.status===0?me:e.error===``?`The session answered ${String(e.status)}.`:e.error}async function V(e){let t=await R.session(e).current();return t.status===404?{ok:!1,error:t.ok||t.error===``?he:t.error}:t.ok?z(t.data)?{ok:!0,detail:t.data}:{ok:!1,error:`The session answered with no plan.`}:{ok:!1,error:B(t)}}async function ge(e,t,n){let r=await R.session(e).save({body:{expectedHash:t,content:n}});if(r.status===409){let e=r.ok?void 0:r.data,t=z(e)&&typeof e.hash==`string`?e.hash:void 0;return{ok:!1,stale:!0,error:r.ok?`The plan changed since it was opened.`:B(r),...t===void 0?{}:{hash:t}}}return r.ok?{ok:!0,hash:z(r.data)&&typeof r.data.hash==`string`?r.data.hash:``}:{ok:!1,stale:!1,error:B(r)}}var H=`plan-document`,U=`saved`;function _e({sessionId:e,statuses:t,closeTransientTab:n}){let[r,o]=b(void 0),[s,c]=b(void 0),[l,u]=b(!1),[d,f]=b(`preview`),[m,h]=b(void 0),[_,v]=b(!1),[x,S]=b(void 0),C=t[`po-plan-document`]??``;y(()=>{if(e===null)return;let t=!1;return u(!0),V(e).then(e=>{t||(u(!1),e.ok?(o(e.detail),c(void 0),h(void 0),S(void 0)):(o(void 0),c(e.error)))}),()=>{t=!0}},[e,C]);let w=m??r?.content??``,T=async()=>{if(e===null||r===void 0||m===void 0)return;v(!0);let t=await ge(e,r.hash,m);if(v(!1),t.ok){S(U),h(void 0);let t=await V(e);t.ok?o(t.detail):c(t.error)}else S(t.error)};return D(`div`,{"data-testid":`plan-panel`,className:`flex min-h-0 flex-1 flex-col`,children:[D(`header`,{className:`flex shrink-0 items-center gap-2 border-b border-po-border px-4 py-2`,children:[E(`span`,{"data-testid":`plan-title`,className:`min-w-0 flex-1 truncate text-lg font-semibold text-po-hi`,children:r?.title??`plan`}),E(`nav`,{className:`flex shrink-0 items-center gap-1`,children:[`preview`,`source`].map(e=>E(p,{variant:d===e?`outline`:`ghost`,size:`xs`,"data-testid":`plan-view-${e}`,onClick:()=>f(e),children:e},e))}),E(p,{variant:`ghost`,size:`xs`,"data-testid":`plan-close`,onClick:()=>n(H),className:`shrink-0`,children:`close`})]}),l&&r===void 0?E(`p`,{"data-testid":`plan-loading`,className:`px-4 py-3 text-sm text-po-dim`,children:`reading this session's plan…`}):null,s===void 0?null:E(`p`,{"data-testid":`plan-error`,className:`px-4 py-3 text-sm text-po-red`,children:s}),E(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:r===void 0?null:r.unavailable?E(`p`,{"data-testid":`plan-unavailable`,className:`px-4 py-3 text-sm text-po-dim`,children:r.reason??`this plan cannot be shown`}):d===`preview`?E(`div`,{"data-testid":`plan-preview`,className:`flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4 text-base text-po-text`,children:E(i,{text:w})}):D(g,{children:[E(a,{"data-testid":`plan-source`,value:w,path:r.path,onChange:h,className:`min-h-0 flex-1`}),D(`div`,{className:`flex shrink-0 items-center gap-2 border-t border-po-border px-3 py-2`,children:[E(p,{variant:`outline`,size:`xs`,"data-testid":`plan-save`,loading:_,disabled:m===void 0||_,onClick:()=>void T(),children:`save to disk`}),m===void 0?null:E(p,{variant:`ghost`,size:`xs`,"data-testid":`plan-revert`,onClick:()=>h(void 0),children:`discard edits`}),x===void 0?null:E(`span`,{"data-testid":`plan-save-note`,className:x===U?`text-sm text-po-green`:`text-sm text-po-red`,children:x})]})]})}),r===void 0?null:E(`footer`,{"data-testid":`plan-source-path`,className:`shrink-0 truncate border-t border-po-border px-4 py-1.5`,children:E(`span`,{className:`font-mono text-sm text-po-dim`,children:r.path})})]})}function ve(){return{id:H,label:`plan`,panel:_e}}function ye({sessionId:e,statuses:t,openTransientTab:n}){let r=fe(t[I]);return r===void 0?E(`p`,{"data-testid":`activity-summary-plan`,className:`px-1 text-sm text-po-dim`,children:`no plan written yet`}):D(`div`,{"data-testid":`activity-plan`,className:`flex flex-col gap-0.5`,children:[E(p,{variant:`ghost`,size:`card`,"data-testid":`activity-plan-open`,title:`open ${r.title}`,disabled:e===null,onClick:()=>{e!==null&&n(ve())},className:`min-w-0 gap-0.5 rounded-md px-1 py-1 hover:bg-po-panel`,children:D(`span`,{className:`flex w-full min-w-0 items-center gap-1.5`,children:[E(`span`,{"data-testid":`activity-plan-title`,className:`min-w-0 flex-1 truncate text-left text-base font-semibold text-po-hi`,children:r.title}),r.stamp===``?null:E(`span`,{"data-testid":`activity-plan-stamp`,className:`shrink-0 text-sm tabular-nums text-po-dim`,children:r.stamp})]})}),E(`p`,{className:`px-1 text-sm leading-relaxed text-po-dim`,children:`open to read or edit; the agent reads what you save.`})]})}var be=se({slot:`activity.plan`,id:`plan`,component:ye}),xe=r({id:`plan.toggle`,path:[{key:`p`,label:`plan`,detail:`read-only planning modes`},{key:`e`,label:`toggle`,detail:`enter or leave read-only planning`}],command:`minor plan`}),Se=oe({name:`plan`,icon:n,keys:`p e`,statusKey:`plan-mode`,order:20});function Ce({dialog:e,answer:n,cancel:r,defaultExpanded:i=!0}){let[a,o]=b(i),[s,l]=b(0),u=x(null);return y(()=>u.current?.querySelector(`[role="listbox"]`)?.focus(),[e.id]),D(d,{ref:u,open:a,onOpenChange:o,role:`group`,"aria-label":`Plan review`,"data-testid":`plan-review-prompt`,className:`flex min-w-0 flex-col overflow-hidden`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),r())},children:[E(t,{asChild:!0,children:D(p,{variant:`ghost`,"aria-label":a?`Collapse plan review`:`Expand plan review`,className:`h-11 w-full justify-between rounded-none px-3.5`,children:[E(ie,{children:`plan review`}),a?null:E(`span`,{className:`ml-auto text-sm font-normal text-po-dim`,children:`Awaiting decision`}),E(a?v:ae,{size:16})]})}),D(w,{children:[D(`div`,{className:`flex flex-col gap-1 px-3.5 pb-2`,children:[E(`p`,{className:`text-base font-semibold leading-relaxed text-po-hi`,children:e.title}),E(`p`,{className:`text-sm leading-relaxed text-po-dim`,children:`Review the plan in the conversation before choosing what happens next.`})]}),E(c,{options:e.options,cursor:s,onCursorChange:l,onSelect:n,onFocus:e=>{let t=Array.from(e.currentTarget.children).indexOf(e.target);t!==-1&&l(t)},tabIndex:-1,onKeyDown:t=>{ee(t,{options:e.options,cursor:s,onCursorChange:l,onSelect:n})},testIdPrefix:`plan-review-option`,className:`max-h-48 px-3.5 pb-3 outline-none`}),D(`div`,{className:`flex items-center gap-2 border-t border-po-border-soft px-3.5 py-2`,children:[D(`span`,{className:`text-sm text-po-dim`,children:[te(e.options.length),` · `,E(_,{children:`esc`}),` cancels`]}),E(p,{variant:`outline`,size:`sm`,"data-testid":`plan-review-cancel`,className:`ml-auto`,onClick:r,children:`cancel`})]})]})]})}var we=[`record_debug_evidence`,`run_fable_plan`,`write_plan`,`complete_plan`];function Te(e){return e.method===`select`&&e.title===`Plan complete. What would you like to do?`&&e.options.length===L.length&&L.every((t,n)=>e.options[n]===t)}var Ee=12,De=72,W=[[`logs`,`log`],[`correlatedTraceEvidence`,`trace`],[`processOutput`,`process output`],[`browserConsoleEvidence`,`console entry`],[`correlationIds`,`correlation id`],[`timestamps`,`timestamp`],[`verifiedFacts`,`verified fact`],[`hypotheses`,`hypothesis`],[`unavailableEvidence`,`unavailable item`]],Oe=[[`goal`,`goal`],[`constraints`,`constraint`],[`decisions`,`decision`],[`verifiedFindings`,`verified finding`],[`inferredFindings`,`inferred finding`],[`unresolvedQuestions`,`open question`]];function G(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function K(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 q(e,t){let n=e?.[t];return typeof n==`string`&&K(n)||void 0}function ke(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ae(e,t){let n=e[t];return Array.isArray(n)?n.length:0}function J(e,t){return e===1?t:t.endsWith(`y`)?`${t.slice(0,-1)}ies`:`${t}s`}function je(e){if(e)return e.length>De?`${e.slice(0,69)}…`:e}function Y(e,t){return t.flatMap(([t,n])=>{let r=Ae(e,t);return r>0?[`${r} ${J(r,n)}`]:[]})}function X(e,t,n={}){return{text:e,tone:t,...n}}function Z(e){return e?e.content.flatMap(e=>{let t=G(e);return t?.type===`text`&&typeof t.text==`string`?[t.text]:[]}).join(`
2
- `):``}function Me(e,t){let n=e.split(`
3
- `).map(e=>e.trimEnd()).filter(e=>e.length>0),r=t?n:n.slice(0,Ee),i=r.map(e=>X(e,`text`));return n.length>r.length&&i.push(X(`… ${n.length-r.length} more lines`,`dim`)),i}function Ne(e,t){if(e===`record_debug_evidence`){let e=je(q(t,`issue`));return{action:`record evidence`,...e?{detail:e}:{},metadata:Y(t,W)}}if(e===`run_fable_plan`){let e=Y(t,Oe);return q(t,`currentPlan`)&&e.push(`with current plan`),{action:`fable draft`,metadata:e}}if(e===`write_plan`)return{action:`save plan`,metadata:[]};let n=q(t,`decision`);return{action:n?`decide ${n}`:`request approval`,metadata:[]}}function Pe(e,t,n){let r=[G(t?.details)?.recorded===!0?X(`✓ evidence recorded as planning context`,`success`):X(`○ ${K(Z(t))||`not recorded`}`,`muted`)];if(!n.expanded)return r;for(let[t,n]of[[`issue`,`issue`],[`expectedBehavior`,`expected`],[`reproductionAttempt`,`reproduction`],[`actualBehavior`,`actual`]]){let i=q(e,t);i&&r.push(X(`${n} ${i}`,`text`,{label:n}))}for(let[t,n]of W){let i=e[t],a=Array.isArray(i)?i.filter(e=>typeof e==`string`):[];a.length!==0&&(r.push(X(J(a.length,n),`hi`,{bold:!0})),r.push(...a.map(e=>X(K(e),`text`,{indent:!0}))))}return r}function Fe(e,t){let n=G(e?.details),r=Z(e);if(n?.started!==!0){let e=q(n,`errorCode`);return[X(`○ ${K(r)||`fable planning did not start`}${e?` · ${e}`:``}`,`muted`)]}let i=q(n,`status`)??`unknown`,a=typeof n?.draft==`string`?n.draft:void 0,o=q(n,`errorCode`);if(!a)return[X(`✗ fable planning ${i}${o?` · ${o}`:``}`,`error`)];let s=i===`completed`;return[X(`${s?`✓`:`!`} fable draft · ${i}${o?` · ${o}`:``}`,s?`success`:`warning`,{bold:!0}),...Me(a,t.expanded)]}function Ie(e,t){let n=G(e?.details),r=q(n,`path`);if(t.isPartial)return[X(`◐ ${q(n,`phase`)??`checking`}${r?` ${r}`:``}`,`warning`)];let i=ke(n,`durationMs`);if(n?.written===!0)return[X(`✓ wrote ${r??`the plan`}${i===void 0?``:` · ${i}ms`}`,`success`)];let a=[X(`○ ${K(Z(e))||`plan not written`}`,`muted`)];return r&&a.push(X(`path ${r}`,`dim`)),a}function Le(e){let t=K(Z(e));return G(e?.details)?.exited===!0?[X(`✓ plan mode exited${t?` · ${t}`:``}`,`success`)]:[X(`○ staying in plan mode${t?` · ${t}`:``}`,`muted`)]}function Re(e){return K(Z(e))}function Q(e,t,n,r){return r.isError?[X(`✗ ${Re(n)||`${e} failed`}`,`error`)]:e===`record_debug_evidence`?Pe(t,n,r):e===`run_fable_plan`?r.isPartial?[X(`◐ drafting with the local Fable broker`,`warning`)]:Fe(n,r):e===`write_plan`?Ie(n,r):r.isPartial?[X(`◐ waiting for the review decision`,`warning`)]:Le(n)}function ze({toolName:t,args:n,result:r,running:i,isError:a}){let o=Ne(t,n),s=Q(t,n,r,{expanded:!1,isError:a,isPartial:i}),c=Q(t,n,r,{expanded:!0,isError:a,isPartial:i});return E(e,{tone:h({running:i,isError:a}),expandable:c.length>s.length,children:({expanded:e})=>D(g,{children:[E(l,{title:o.action,children:E(`span`,{"data-testid":`tool-call-${t}`,title:[o.detail,...o.metadata].filter(Boolean).join(` · `)||void 0,className:`min-w-0 flex-1 truncate text-po-dim`,children:[o.detail,...o.metadata].filter(Boolean).join(` · `)})}),(e?c:s).length>0?E(C,{"data-testid":`tool-result-${t}`,children:E(f,{lines:e?c:s})}):null]})})}var Be=u({tools:[...we],message:ze,prompt:{claims:Te,component:Ce}}),$=(e,t)=>t===void 0?void 0:{...e,...t},Ve=o({id:`plan`,host:{get settingsSections(){return[$({id:`plan`},ce)]}},workspace:{get settingsSections(){return[$({id:`plan`},le)]}},session:{get activityGroups(){return[$({name:`plan`},pe)]},get fills(){return[$({slot:`activity.plan`,id:`plan`},be)]},get leaderBindings(){return[$({id:`plan.toggle`},xe)]},get minorModes(){return[$({name:`plan`},Se)]},get toolRenderers(){return[$({tools:[`plan`]},Be)]}}});export{Ve as webPlugin};
@@ -1 +0,0 @@
1
- import{Er as e,Fr as t}from"../chunks/po-web-runtime-DtS_FP_f.js";var n=e({name:`profile`,command:`profile`,statusKey:`po-profile`,emptyLabel:`None`,order:10}),r=(e,t)=>t===void 0?void 0:{...e,...t},i=t({id:`profile`,session:{get selectionAxes(){return[r({name:`profile`},n)]}}});export{i as webPlugin};
@@ -1 +0,0 @@
1
- import{A as e,Fr as t,M as n,Mr as r,N as i,Sn as a,Xt as o,_n as s,a as c,en as l,j as u,lr as d,o as f,s as p,un as m}from"../chunks/po-web-runtime-DtS_FP_f.js";function h(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function g(e){let t=h(e.offset),n=h(e.limit);return{path:typeof e.path==`string`?e.path:``,details:[t===void 0?void 0:`from ${t}`,n===void 0?void 0:`${n} lines`].filter(e=>e!==void 0&&e.length>0)}}var _=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`]);function v(e){return e.flatMap(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return[];let t=e;return t.type===`image`&&typeof t.data==`string`&&typeof t.mimeType==`string`&&_.has(t.mimeType)?[{data:t.data,mimeType:t.mimeType}]:[]})}function y({args:t,result:r,output:h,running:_,isError:y,fileTabFor:b,openTransientTab:x}){let S=g(t),C=v(r?.content??[]),w=b(S.path),T=r===null||y?null:m(r,h,`read`,!0);return f(e,{tone:a({running:_,isError:y}),expandable:!0,defaultExpanded:!1,children:({expanded:e})=>p(c,{children:[f(n,{title:`read`,children:p(`span`,{"data-testid":`tool-call-read`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[f(o,{path:S.path,...w===void 0?{}:{onOpen:()=>x(w)}}),S.details.length>0?p(`span`,{className:`shrink-0 text-po-faint`,children:[`· `,S.details.join(` · `)]}):null]})}),e?y?p(u,{"data-testid":`tool-result-read`,className:`flex flex-col`,children:[f(i,{tone:`error`,children:`failed`}),s(r,h).map((e,t)=>f(`span`,{className:`whitespace-pre-wrap break-words text-po-red`,children:e},`${String(t)}-${e}`))]}):T===null?_?f(u,{"data-testid":`tool-result-read`,children:f(i,{tone:`running`,children:`running`})}):null:T.shown.length===0&&T.notice===void 0&&C.length===0?null:p(u,{"data-testid":`tool-result-read`,className:`flex flex-col gap-1`,children:[f(d,{lines:T.shown,gutter:T.gutter,path:S.path}),C.map((e,t)=>f(l,{src:`data:${e.mimeType};base64,${e.data}`,alt:`Read result ${String(t+1)}`,"data-testid":`tool-result-read-image`,className:`h-auto max-h-96 max-w-full rounded-md border border-po-border-soft object-contain`},`${e.mimeType}:${String(t)}`)),T.notice===void 0?null:f(`span`,{className:`text-po-faint`,children:T.notice})]}):null]})})}var b=r({message:y}),x=(e,t)=>t===void 0?void 0:{...e,...t},S=t({id:`read`,session:{get toolRenderers(){return[x({tools:[`read`]},b)]}}});export{S as webPlugin};
@@ -1,8 +0,0 @@
1
- import{A as e,B as t,Bt as n,Dr as r,Fr as i,H as a,It as o,J as s,M as c,Mr as l,N as u,Qt as d,Rr as f,Sn as p,Un as m,W as h,_ as g,_r as _,a as v,ar as y,bn as b,d as x,fr as S,g as C,h as w,hr as T,i as E,ir as ee,j as D,k as te,l as ne,m as re,mr as O,n as k,nr as A,o as j,or as ie,qn as M,qt as ae,rn as N,s as P,tr as oe,tt as se,u as ce,xr as F}from"../chunks/po-web-runtime-DtS_FP_f.js";var I=`/runners start`,L={command:'exec "${SHELL:-/bin/bash}" -l',name:`shell`,interactive:!0};function R(e,t){let n=t.trim()===``?{}:{cwd:t};return e.trim()===``?{...L,...n}:{command:e,...n,preferInteractive:!0}}function z(e){return/\s/u.test(e)?`"${e}"`:e}function B(e){let t=e.cwd?.trim()??``,n=e.name?.trim()??``;return[I,...n===``?[]:[`name=${z(n)}`],...t===``?[]:[`cwd=${z(t)}`],...e.interactive===!0?[`interactive=true`]:e.preferInteractive===!0?[`interactive=prefer`]:[],`--`,e.command.trim()].join(` `)}var V=`runner_runs`,H=`/runners stop`,U=r({runs:[],stopRequested:[]});function W(e,t=Date.now()){return e.state===`running`&&t-Date.parse(e.startedAt)>3e3}var G={subscribe(e){let t,n=()=>{clearTimeout(t);let r=Date.now(),i=1/0;for(let e of Object.values(U.store.state))if(e)for(let t of e.runs){if(t.state!==`running`)continue;let e=Date.parse(t.startedAt)+3001;e>r&&(i=Math.min(i,e))}Number.isFinite(i)&&(t=setTimeout(()=>{e(),n()},Math.min(i-r,2147483647)))},r=U.store.subscribe(()=>{e(),n()});return n(),()=>{r.unsubscribe(),clearTimeout(t)}},isActive(e){return U.select(U.store.state,e).runs.some(e=>W(e))}};function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function q(e,t,n){e(t,{type:`prompt`,message:`${H} ${n}`}),U.update(t,e=>({...e,stopRequested:[...e.stopRequested.filter(e=>e!==n),n]}))}function le(e,t,n){e(t,{type:`prompt`,message:B(n)})}var ue=U.channel({channel:V,parse(e){if(!K(e)||!Array.isArray(e.runs))return null;let t=e.startFailure;return{runs:e.runs.filter(K),...typeof e.sessionDirectory==`string`?{sessionDirectory:e.sessionDirectory}:{},...K(t)&&typeof t.id==`string`&&typeof t.message==`string`?{startFailure:{id:t.id,message:t.message}}:{}}},reduce(e,t){let n=new Set(t.runs.filter(e=>e.state===`running`).map(e=>e.id));return{...t,stopRequested:e.stopRequested.filter(e=>n.has(e))}}});function de(e,t){let n=Date.parse(e);if(Number.isNaN(n))return`unknown`;let r=Math.max(0,Math.floor((t-n)/1e3));if(r<60)return`${r}s`;let i=Math.floor(r/60);if(i<60)return`${i}m`;let a=Math.floor(i/60);return a<24?`${a}h`:`${Math.floor(a/24)}d`}function fe(e,t,n,r={}){let i=e.split(`
2
- `);i.length>0&&i[i.length-1]===``&&i.pop(),r.dropPartialTail===!0&&i.length>0&&i.pop();let a=[...i,...t],o=a.slice(-n);return{lines:o,hidden:a.length-o.length}}function pe(e,t){let n=Math.max(1,e-t+1);return Array.from({length:t},(e,t)=>n+t)}function me(e,t,n){return e&&!t&&n}function he(e,t){return e===``||e===t?t===void 0?`session directory`:t.split(`/`).pop()??t:t!==void 0&&e.startsWith(`${t}/`)?e.slice(t.length+1):e}function ge(e,t,n){let r=new Set([...e,t]);return r.delete(``),n!==void 0&&r.delete(n),[...r]}function _e(e){return e===void 0?{tone:`neutral`,label:`gone`}:e.state===`running`?{tone:`running`,label:`running`}:e.exit===void 0||e.exit.reason===`stopped`?{tone:`neutral`,label:`stopped`}:e.exit.reason===`completed`&&(e.exit.code===0||e.exit.code===null)?{tone:`ok`,label:`done`}:{tone:`error`,label:e.exit.reason.replace(`_`,` `)}}function ve({command:e,onCommandChange:n,cwd:r,onCwdChange:i,sessionDirectory:a,folders:o,problem:c,onLaunch:l,defaultFolderOpen:u=!1}){let[f,p]=C(u),[m,g]=C(``),_=he(r,a),v=e=>{i(e),g(``),p(!1)},x=[{value:``,title:`Session directory`,subtitle:a??`Where this session started`},...ge(o,r,a).map(e=>({value:e,title:he(e,a),subtitle:e}))];return P(`div`,{className:`flex shrink-0 flex-col gap-1.5 border-b border-po-border-soft px-3 py-3 sm:px-[26px]`,children:[P(`div`,{className:`flex flex-wrap items-center gap-2 sm:flex-nowrap`,children:[P(`span`,{className:`relative flex min-w-0 flex-1 basis-full items-center sm:basis-auto`,children:[j(`span`,{"aria-hidden":!0,className:`pointer-events-none absolute left-3 font-mono text-base text-po-faint`,children:`$`}),j(S,{size:`lg`,"data-testid":`runners-panel-command`,"aria-label":`Command to run`,value:e,placeholder:`a command, like pnpm dev`,autoComplete:`off`,spellCheck:!1,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&l()},className:`w-full pl-7 font-mono`})]}),P(h,{open:f,onOpenChange:p,children:[j(s,{asChild:!0,children:P(d,{variant:`outline`,size:`lg`,"data-testid":`runners-panel-cwd`,"aria-label":`Runs in ${_}`,"aria-invalid":c!==void 0||void 0,title:r===``?a:r,className:`max-w-56 gap-1.5 px-3 font-mono ${c===void 0?``:`border-po-red`}`,children:[j(y,{className:`h-3.5 w-3.5 shrink-0 text-po-faint`}),j(`span`,{className:`truncate`,children:_}),j(b,{className:`size-3.5 shrink-0 opacity-60`})]})}),j(t,{side:`bottom`,align:`start`,title:`Runs in`,items:x,value:[r],onSelect:v,footer:P(`span`,{className:`relative flex items-center px-3 py-2`,children:[j(y,{className:`pointer-events-none absolute left-5.5 h-3.5 w-3.5 text-po-faint`}),j(S,{"data-testid":`runners-panel-cwd-path`,"aria-label":`Another folder`,value:m,placeholder:`another folder, like packages/web`,spellCheck:!1,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m.trim()!==``&&v(m.trim())},className:`w-full pl-8 font-mono`})]})})]}),j(d,{variant:`primary`,size:`lg`,"data-testid":`runners-panel-run`,onClick:l,children:e.trim()===``?`Open shell`:`Run`})]}),c===void 0?j(`span`,{className:`text-sm text-po-dim`,children:`Runs in its own terminal and keeps going after Po's turn ends. Leave it empty for a plain shell.`}):P(`span`,{role:`alert`,"data-testid":`runners-panel-problem`,className:`flex items-center gap-1.5 text-sm text-po-red`,children:[j(M,{className:`size-3.5 shrink-0`}),c]})]})}var J=`runId`,ye=`screen`,be=`append`,Y={lines:`lines`,grep:`grep`,ignoreCase:`ignoreCase`,contextLines:`contextLines`,from:`from`,generation:`generation`},xe={log:{method:`GET`,path:`/runners/:${J}/log`,query:[Y.lines,Y.grep,Y.ignoreCase,Y.contextLines],response:void 0},logStream:{method:`GET`,path:`/runners/:${J}/log/stream`,query:[Y.from],stream:!0},screenStream:{method:`GET`,path:`/runners/:${J}/screen/stream`,query:[Y.from],stream:!0},logRead:{method:`GET`,path:`/runners/:${J}/log/read`,query:[Y.from],response:void 0},screenRead:{method:`GET`,path:`/runners/:${J}/screen/read`,query:[Y.from,Y.generation],response:void 0},input:{method:`POST`,path:`/runners/:${J}/screen/input`}},X=O(xe,{scopes:[`session`],basePath:`runner`,transport:(e,t)=>k.fetch(e,t),sessionAddress:f}),Se=`The cockpit hub is unreachable.`;function Ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function we(e,t,n={},r){let i=await X.session(e).log({params:{[J]:t},query:{[Y.lines]:n.lines,[Y.grep]:n.grep===``?void 0:n.grep,[Y.ignoreCase]:n.ignoreCase===!0||void 0,[Y.contextLines]:n.contextLines},...r===void 0?{}:{signal:r}});return i.ok?!Ce(i.data)||typeof i.data.text!=`string`?{error:`The hub answered ${String(i.status)}.`}:{slice:i.data}:i.status===0?{error:r?.aborted===!0?``:Se}:{error:i.error===``?`The hub answered ${String(i.status)}.`:i.error}}var Te=5,Ee=500;function De(e,t,n,r){let i=n,a=0,o=!1,s,c,l=()=>{if(o)return;let n=new EventSource(X.session(e).logStream.url({params:{[J]:t},query:{[Y.from]:i}}));s=n,n.addEventListener(be,e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!Ce(t)||!Array.isArray(t.lines))return;let s=t;typeof s.offset==`number`&&(i=s.offset),a=0,s.ended===!0&&(o=!0,n.close()),r.onEvent(s)}),n.addEventListener(`error`,()=>{n.close(),!o&&(a+=1,a>Te?r.onLost():c=setTimeout(l,Ee*2**(a-1)))})};return l(),{close:()=>{o=!0,c!==void 0&&clearTimeout(c),s?.close()}}}var Oe=`runner-log-`,ke=2e3,Ae=2,je=200,Me=24,Z=1024,Ne=Z*Z;function Pe(e){let t=e.id;return{id:`${Oe}${t}`,label:`log · ${e.name}`,panel:e=>j(Re,{...e,runId:t})}}function Fe(e){return e<Z?`${e} B`:e<Ne?`${(e/Z).toFixed(1)} KB`:`${(e/Ne).toFixed(1)} MB`}function Ie(e,t,n){return t===``?!1:n?e.toLowerCase().includes(t.toLowerCase()):e.includes(t)}function Le({number:e,line:t,matched:n,dimmed:r}){return P(`div`,{"data-testid":`runner-log-row`,"data-matched":n,className:`flex min-w-0 gap-2`,children:[e===void 0?null:j(`span`,{className:`w-12 shrink-0 select-none text-right font-mono text-sm leading-relaxed text-po-faint`,children:e}),j(`span`,{"aria-hidden":!0,className:`w-4 shrink-0 select-none font-mono text-sm leading-relaxed ${n?`text-po-yellow`:`text-po-faint`}`,children:n?`>>`:``}),j(oe,{line:t,className:`min-w-0 flex-1 whitespace-pre-wrap break-words font-mono text-sm leading-relaxed ${r?`text-po-dim`:`text-po-text`}`})]})}function Re({sessionId:e,runId:t,sendSessionFrame:n,onTerminal:r}){let{runs:i,stopRequested:a}=E(U.store,t=>U.select(t,e)),s=i.find(e=>e.id===t),[c,l]=C(``),[u,f]=C(``),[p,m]=C(!1),[h,g]=C(Ae),[_,y]=C(!0),[T,ee]=C(void 0),[D,te]=C(void 0),[O,k]=C([]),[A,ie]=C(void 0),[M,ae]=C(!0),[N,oe]=C(!1),F=w(null),I=w(null),L=u!==``,R=me(_,L,T?.running===!0);x(()=>{let e=setTimeout(()=>f(c),je);return()=>clearTimeout(e)},[c]);let z=ne(n=>{e!==null&&we(e,t,L?{grep:u,ignoreCase:p,contextLines:h}:{},n).then(e=>{n.aborted||(`error`in e?e.error!==``&&ie(e.error):(ie(void 0),k([]),ee(e.slice),te(e.slice.completeBytes)))})},[e,t,L,u,p,h]);x(()=>{let e=new AbortController;return z(e.signal),()=>e.abort()},[z]),x(()=>{if(!R||e===null||D===void 0)return;let n=De(e,t,D,{onEvent:e=>{e.lines.length>0&&k(t=>[...t,...e.lines].slice(-2e3)),e.ended===!0&&y(!1)},onLost:()=>y(!1)});return()=>n.close()},[R,e,t,D]);let B=T!==void 0&&T.exists&&T.completeBytes<T.fileSize,V=fe(T?.text??``,O,ke,{dropPartialTail:R&&B}),H=re(()=>T===void 0?[]:L?T.lineNumbers??[]:pe(T.totalLines+O.length-(R&&B?1:0),V.lines.length),[T,L,O.length,R,B,V.lines.length]);x(()=>{R&&M&&F.current?.scrollIntoView({block:`end`})},[R,M,V.lines.length]);let W=()=>{let e=I.current;e!==null&&ae(e.scrollHeight-e.scrollTop-e.clientHeight<=Me)},G=_e(s),K=s!==void 0&&a.includes(s.id);return P(`div`,{"data-testid":`runner-log-panel`,className:`flex min-h-0 flex-1 flex-col`,children:[P(`div`,{className:`flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-po-border-soft px-3 py-2 sm:h-11 sm:flex-nowrap sm:gap-2.5 sm:px-[26px] sm:py-0`,children:[j(`span`,{"data-testid":`runner-log-name`,className:`shrink-0 truncate text-base font-semibold text-po-hi`,children:s?.name??t}),j(o,{tone:G.tone,size:`md`,"data-testid":`runner-log-state`,children:G.label}),s?P(v,{children:[j(ze,{run:s}),j(`span`,{className:`shrink-0 text-sm text-po-dim`,children:`pid ${String(s.pid)} · ${s.backend}${s.interactive?` · tty`:``}`})]}):j(`span`,{"data-testid":`runner-log-gone`,className:`text-sm text-po-dim`,children:`no longer listed; its log stays readable`}),j(`span`,{className:`min-w-0 flex-1`}),r?j(d,{variant:`outline`,size:`sm`,"data-testid":`runner-log-terminal`,onClick:r,children:`Back to terminal`}):null,s!==void 0&&s.state===`running`&&e!==null?j(d,{variant:K?`outline`:`danger-outline`,size:`sm`,"data-testid":`runner-log-stop`,disabled:K,title:K?`stop requested; the runner reports its own exit`:`ask the runtime to stop this runner`,onClick:()=>q(n,e,s.id),children:K?`Stopping…`:`Stop`}):null]}),s?j(`div`,{className:`shrink-0 border-b border-po-border-soft px-3 py-3 sm:px-[26px]`,children:P(`div`,{className:`flex items-start gap-2 rounded-md bg-po-deep px-3 py-2`,children:[P(`div`,{className:`flex min-w-0 flex-1 flex-col gap-1`,children:[P(`span`,{"data-testid":`runner-log-command`,title:N?void 0:`${s.command}\nin ${s.cwd}`,className:`font-mono text-base text-po-hi ${N?`break-all`:`truncate`}`,children:[P(`span`,{"aria-hidden":!0,className:`select-none text-po-faint`,children:[`$`,` `]}),s.command]}),N?P(`span`,{className:`break-all font-mono text-sm text-po-dim`,children:[`in `,s.cwd]}):null]}),j(`button`,{type:`button`,"data-testid":`runner-log-command-toggle`,"aria-expanded":N,"aria-label":N?`Collapse command`:`Expand command`,className:`flex size-6 shrink-0 items-center justify-center rounded text-po-faint hover:text-po-hi`,onClick:()=>oe(e=>!e),children:j(b,{className:`size-4 transition-transform ${N?`rotate-180`:``}`})})]})}):null,P(`div`,{className:`flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-po-border-soft px-3 py-2 sm:flex-nowrap sm:gap-2.5 sm:px-[26px]`,children:[P(`span`,{className:`relative flex min-w-0 flex-1 items-center sm:w-72 sm:flex-none`,children:[j(se,{className:`pointer-events-none absolute left-2.5 h-3.5 w-3.5 text-po-faint`}),j(S,{size:`md`,"data-testid":`runner-log-search`,value:c,placeholder:`Search output`,onChange:e=>l(e.target.value),className:`w-full pl-8`})]}),j(d,{variant:p?`subtle`:`outline`,size:`sm`,"data-testid":`runner-log-ignore-case`,"aria-pressed":p,title:`match regardless of case`,onClick:()=>m(e=>!e),children:p?`Any case`:`Match case`}),j(d,{variant:h>0&&L?`subtle`:`outline`,size:`sm`,"data-testid":`runner-log-context`,disabled:!L,title:`lines of context kept either side of a match`,onClick:()=>g(e=>e===0?Ae:0),children:`± ${String(h)} lines`}),j(`span`,{className:`min-w-0 flex-1`}),P(`span`,{"data-testid":`runner-log-stats`,className:`min-w-0 basis-full truncate text-sm text-po-dim sm:basis-auto`,children:[T===void 0?`reading…`:L?`${String(T.lineCount)} matching of ${T.totalLines.toLocaleString(`en-US`)} lines`:`${R?`tailing`:`showing`} last ${String(V.lines.length)} of ${T.totalLines.toLocaleString(`en-US`)} lines`,V.hidden>0?` · ${V.hidden.toLocaleString(`en-US`)} older hidden`:``]}),j(d,{variant:R?`subtle`:`outline`,size:`sm`,"data-testid":`runner-log-follow`,"aria-pressed":R,disabled:L||T?.running!==!0,title:L?`a filtered view is a snapshot; clear the query to follow`:`follow the log as it grows`,onClick:()=>y(e=>!e),children:L?`Paused while searching`:R?`Following`:`Follow`})]}),P(`div`,{className:`relative min-h-0 flex-1`,children:[P(`div`,{ref:I,onScroll:W,"data-testid":`runner-log-body`,className:`h-full overflow-auto bg-po-deep px-3 py-3 sm:px-[26px]`,children:[A===void 0?T===void 0?j(`p`,{"data-testid":`runner-log-reading`,className:`text-sm text-po-dim`,children:`reading…`}):T.exists===!1?j(`p`,{className:`text-sm text-po-dim`,children:`This runner has not printed anything yet.`}):V.lines.length===0?j(`p`,{className:`text-sm text-po-dim`,children:L?`Nothing matched.`:`The log is empty.`}):V.lines.map((e,t)=>{let n=H[t],r=H[t-1],i=r!==void 0&&n!==void 0&&n-r>1;return P(ce,{children:[i?j(`div`,{"data-testid":`runner-log-gap`,"aria-hidden":!0,className:`select-none py-0.5 pl-14 text-sm leading-relaxed text-po-faint`,children:`⋯`}):null,j(Le,{number:n,line:e,matched:L&&Ie(e,u,p),dimmed:L&&!Ie(e,u,p)})]},n??`row-${String(t)}`)}):j(`p`,{"data-testid":`runner-log-error`,className:`text-sm text-po-red`,children:A}),j(`div`,{ref:F})]}),R&&!M?j(d,{variant:`subtle`,size:`sm`,"data-testid":`runner-log-jump`,title:`scroll back to the newest lines and keep following`,onClick:()=>{ae(!0),F.current?.scrollIntoView({block:`end`})},className:`absolute bottom-3 right-3`,children:`Jump to latest`}):null]}),P(`div`,{className:`flex h-8 shrink-0 items-center gap-2.5 border-t border-po-border-soft px-3 sm:px-[26px]`,children:[j(`span`,{"data-testid":`runner-log-path`,className:`min-w-0 flex-1 truncate font-mono text-sm text-po-dim`,children:s?.logPath??T?.path??``}),T===void 0?null:j(`span`,{className:`shrink-0 text-sm text-po-dim`,children:Fe(T.fileSize)})]})]})}function ze({run:e}){let t=w(null),[n]=C(Date.now);return x(()=>{if(e.exit||e.state!==`running`)return;let n=()=>{let n=t.current?.firstChild;n&&(n.nodeValue=de(e.startedAt,Date.now()))};n();let r=setInterval(n,1e3);return()=>clearInterval(r)},[e.startedAt,e.state,e.exit]),j(`span`,{ref:t,className:`shrink-0 text-sm text-po-dim`,children:de(e.startedAt,e.exit?Date.parse(e.exit.finishedAt):n)})}function Be(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}var Ve=5,He=500;function Ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function We(e,t,n,r){let i=n,a=0,o=!1,s,c,l=()=>{if(o)return;let n=new EventSource(X.session(e).screenStream.url({params:{[J]:t},query:{[Y.from]:i}}));s=n,n.addEventListener(ye,e=>{let t;try{t=JSON.parse(e.data)}catch{return}if(!Ue(t)||typeof t.chunk!=`string`)return;let s=t;typeof s.offset==`number`&&(i=s.offset),a=0,s.ended===!0&&(o=!0,n.close()),r.onEvent(s)}),n.addEventListener(`error`,()=>{n.close(),!o&&(a+=1,a>Ve?r.onLost():c=setTimeout(l,He*2**(a-1)))})};return l(),{close:()=>{o=!0,c!==void 0&&clearTimeout(c),s?.close()}}}async function Ge(e,t,n){let r={text:n};return(await X.session(e).input({params:{[J]:t},body:r})).ok}var Ke=30;function qe({sessionId:e,runId:t,sendSessionFrame:n,openTransientTab:r,onSearch:i}){let{runs:a,stopRequested:s}=E(U.store,t=>U.select(t,e)),c=a.find(e=>e.id===t),[l,u]=C(!1),[f,p]=C(!1),[m,h]=C(!1),g=w(null),_=w([]),v=w(void 0);x(()=>{if(e===null||!m)return;let n=We(e,t,0,{onEvent:e=>{e.chunk!==``&&g.current?.write(Be(e.chunk)),e.ended===!0&&u(!0)},onLost:()=>p(!0)});return()=>n.close()},[e,t,m]),x(()=>()=>{v.current!==void 0&&clearTimeout(v.current)},[]);let y=n=>{e!==null&&(_.current.push(n),v.current===void 0&&(v.current=setTimeout(()=>{let n=_.current.join(``);_.current=[],v.current=void 0,n!==``&&Ge(e,t,n)},Ke)))},b=c?.state===`running`&&!l,S=s.includes(t);return P(`div`,{"data-testid":`runner-shell-panel`,className:`flex min-h-0 flex-1 flex-col`,children:[P(`div`,{className:`flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b border-po-border-soft px-3 py-2 sm:flex-nowrap sm:gap-2.5 sm:px-[26px] sm:py-1.5`,children:[j(`span`,{"data-testid":`runner-shell-name`,className:`shrink-0 truncate text-base font-semibold text-po-hi`,children:c?.name??t}),j(o,{tone:b?`running`:`neutral`,size:`md`,"data-testid":`runner-shell-state`,children:b?`Running`:`Ended`}),c?j(`span`,{className:`min-w-0 truncate font-mono text-sm text-po-dim`,children:c.command}):null,j(`span`,{className:`min-w-0 flex-1`}),f?j(`span`,{"data-testid":`runner-shell-lost`,className:`shrink-0 text-sm text-po-red`,children:`The connection to this terminal dropped. Reopen the runner to attach again.`}):null,c?P(d,{variant:`outline`,size:`sm`,"data-testid":`runner-shell-search`,title:`search everything this runner has printed`,onClick:()=>i?i():r(Pe(c)),className:`gap-1.5`,children:[j(se,{className:`h-3.5 w-3.5`}),`Search output`]}):null,b?j(d,{variant:`outline`,size:`sm`,"data-testid":`runner-shell-interrupt`,title:`send ctrl-c`,onClick:()=>y(``),children:`Ctrl-C`}):null,b&&e!==null?j(d,{variant:S?`outline`:`danger-outline`,size:`sm`,"data-testid":`runner-shell-stop`,disabled:S,title:S?`stop requested; the runner reports its own exit`:`ask the runtime to stop this runner`,onClick:()=>q(n,e,t),children:S?`Stopping…`:`Stop`}):null]}),P(`div`,{className:`relative min-h-0 flex-1 overflow-hidden bg-po-deep px-3 py-2 sm:px-[26px]`,children:[j(ae,{ref:g,"data-testid":`runner-shell-terminal`,onData:e=>y(e),onReady:()=>h(!0)}),m?null:j(`p`,{"data-testid":`runner-shell-reading`,className:`text-sm text-po-dim`,children:`attaching…`})]}),j(`div`,{className:`flex h-8 shrink-0 items-center border-t border-po-border-soft px-3 sm:px-[26px]`,children:j(`span`,{className:`min-w-0 flex-1 truncate text-sm text-po-dim`,children:b?`Typing goes straight to ${c?.name??`the runner`}. Ctrl-C stops what is running.`:`This runner has ended. Its output stays searchable.`})})]})}var Je=3e4,Ye=`runner-runs`;function Xe(){return{id:Ye,label:`runners`,panel:Ze}}function Ze(e){let{sessionId:t,sendSessionFrame:n}=e,r=E(U.store,e=>U.select(e,t)),i=r.runs.filter(e=>e.state===`running`),[a,o]=C(``),[s,c]=C(``),[l,u]=C(void 0),[f,p]=C(void 0),h=w(null),g=w(``),_=w(void 0),y=i.find(e=>e.id===l)??i[0],b=()=>{t!==null&&(h.current=new Set(r.runs.map(e=>e.id)),clearTimeout(_.current),_.current=setTimeout(()=>{h.current=null},Je),le(n,t,R(a,s)),g.current=a,o(``))};x(()=>{let e=h.current;if(e===null)return;let t=r.runs.find(t=>t.state===`running`&&!e.has(t.id));t&&(h.current=null,clearTimeout(_.current),u(t.id))},[r.runs]);let S=r.startFailure?.id;return x(()=>{S!==void 0&&h.current!==null&&(h.current=null,clearTimeout(_.current),o(g.current))},[S]),x(()=>()=>clearTimeout(_.current),[]),P(`div`,{"data-testid":`runners-panel`,className:`flex min-h-0 flex-1 flex-col`,children:[P(`div`,{className:`flex h-11 shrink-0 items-center gap-2.5 border-b border-po-border-soft px-3 sm:px-[26px]`,children:[j(`span`,{className:`text-lg font-semibold text-po-hi`,children:`Runners`}),j(`span`,{"data-testid":`runners-panel-count`,className:`text-sm text-po-dim`,children:i.length===0?`Nothing running`:`${String(i.length)} running`})]}),t===null?null:j(ve,{command:a,onCommandChange:o,cwd:s,onCwdChange:c,folders:i.map(e=>e.cwd),...r.sessionDirectory===void 0?{}:{sessionDirectory:r.sessionDirectory},...r.startFailure===void 0?{}:{problem:r.startFailure.message},onLaunch:b}),y===void 0?j(A,{"data-testid":`runners-panel-empty`,className:`px-4 py-8`,title:`Nothing running yet`,description:t===null?`Open a session to start a runner.`:`Type a command above, like pnpm dev, and it opens here as a live terminal.`}):P(v,{children:[j(`div`,{"data-testid":`runners-panel-picker`,className:`flex shrink-0 flex-wrap gap-1.5 px-3 pt-3 sm:px-[26px]`,children:i.map(e=>P(d,{variant:e===y?`subtle`:`ghost`,size:`sm`,"data-testid":`runners-panel-pick-${e.id}`,"aria-pressed":e===y,title:e.command,onClick:()=>u(e.id),className:`gap-1.5 ${e===y?`text-po-hi`:``}`,children:[j(m,{tone:`yellow`,pulse:!0}),e.name]},e.id))}),j(`div`,{className:`mt-3 flex min-h-0 flex-1 flex-col border-t border-po-border-soft`,children:y.interactive&&f!==y.id?j(qe,{...e,runId:y.id,onSearch:()=>p(y.id)},y.id):j(Re,{...e,runId:y.id,...y.interactive?{onTerminal:()=>p(void 0)}:{}},y.id)})]})]})}var Qe=T({keys:`r l`,icon:a,activeSource:G,transientTab:Xe,order:20}),$e=_(ue),et=5;function tt(e){for(let t=e.length-1;t>=0;--t){let n=N(e[t]??``).map(e=>e.text).join(``).trim();if(n.length>0)return n}}function nt(e,t,n){let[r,i]=C(void 0);return x(()=>{if(!n||e===null)return;let r=!0,a,o=new AbortController;return we(e,t,{lines:et},o.signal).then(n=>{if(!r||`error`in n)return;let o=tt(n.slice.text.split(`
3
- `));o!==void 0&&i({runId:t,text:o}),n.slice.running&&(a=De(e,t,n.slice.completeBytes,{onEvent:e=>{let n=tt(e.lines);r&&n!==void 0&&i({runId:t,text:n})},onLost:()=>void 0}))}),()=>{r=!1,o.abort(),a?.close()}},[e,t,n]),n&&r?.runId===t?r.text:void 0}function rt({sessionId:e,sendSessionFrame:t,openTransientTab:n}){let r=E(U.store,t=>U.select(t,e)),i=()=>r.runs.filter(e=>W(e)).length;g(G.subscribe,i,i);let a=r.runs.filter(e=>W(e));return a.length===0?P(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1`,children:[j(`p`,{"data-testid":`activity-summary-runners`,className:`text-sm text-po-dim`,children:`Idle`}),e===null?null:P(d,{variant:`link`,size:`sm`,"data-testid":`activity-runner-launch`,className:`h-auto gap-1 px-0 text-po-green`,onClick:()=>n(Xe()),children:[`Launch a runner`,j(te,{"aria-hidden":!0,className:`size-3.5`})]})]}):j(`div`,{"data-testid":`activity-runner-runs`,className:`flex flex-col gap-0.5`,children:a.map(i=>j(it,{run:i,stopRequested:r.stopRequested.includes(i.id),sessionId:e,sendSessionFrame:t,openTransientTab:n},i.id))})}function it({run:e,stopRequested:t,sessionId:n,sendSessionFrame:r,openTransientTab:i}){let a=nt(n,e.id,e.state===`running`);return P(d,{variant:`ghost`,size:`card`,"data-testid":`activity-runner-${e.id}`,"data-runner-tone":`running`,title:`open this runner's log`,onClick:()=>{n!==null&&i(Pe(e))},className:`min-w-0 gap-0.5 rounded-md px-1 py-1 hover:bg-po-panel`,children:[P(`span`,{className:`flex min-w-0 items-center gap-1.5`,children:[j(m,{tone:`yellow`,pulse:!0}),j(`span`,{className:`min-w-0 flex-1 truncate text-left text-base font-semibold text-po-hi`,children:e.name}),P(`span`,{className:`shrink-0 text-sm text-po-dim`,children:[j(ze,{run:e}),e.interactive?` · tty`:``]}),n===null?null:j(d,{asChild:!0,variant:t?`outline`:`danger-outline`,size:`xs`,"data-testid":`activity-runner-stop-${e.id}`,"data-stopping":t,title:t?`stop requested; the runner reports its own exit`:`ask the runtime to stop this runner`,className:`px-1.5`,children:j(`span`,{role:`button`,tabIndex:t?-1:0,"aria-disabled":t,onClick:i=>{i.stopPropagation(),t||q(r,n,e.id)},onKeyDown:i=>{(i.key===`Enter`||i.key===` `)&&(i.preventDefault(),i.stopPropagation(),t||q(r,n,e.id))},children:t?`stopping…`:`stop`})})]}),j(`span`,{"data-testid":`activity-runner-detail-${e.id}`,"data-detail":a===void 0?`command`:`tail`,className:`truncate pl-3 text-left text-sm text-po-dim`,children:a??e.command})]})}var at=F({component:rt}),ot=`…`,st=` … `,ct=160,lt=12,Q=1024,ut=Q*Q,dt=/(?<![\w.-])(?:\/Users|\/home)\/[^/\s]+(?=\/|\s|$)/g;function ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pt(e){if(!ft(e))return{};let t={};return typeof e.id==`string`&&(t.id=e.id),typeof e.runner==`string`&&(t.runner=e.runner),(typeof e.exitCode==`number`||e.exitCode===null)&&(t.exitCode=e.exitCode),typeof e.logPath==`string`&&(t.logPath=e.logPath),typeof e.fileSize==`number`&&(t.fileSize=e.fileSize),typeof e.lines==`number`&&(t.lines=e.lines),e.timedOut===!0&&(t.timedOut=!0),e.promoted===!0&&(t.promoted=!0),typeof e.reason==`string`&&(t.reason=e.reason),typeof e.tail==`string`&&(t.tail=e.tail),typeof e.tailLines==`number`&&(t.tailLines=e.tailLines),typeof e.sequenceId==`string`&&(t.sequenceId=e.sequenceId,Array.isArray(e.stages)&&(t.stages=e.stages.flatMap(e=>!ft(e)||!Number.isInteger(e.index)||Number(e.index)<0||typeof e.state!=`string`?[]:[{index:Number(e.index),state:e.state,...typeof e.logPath==`string`?{logPath:e.logPath}:{}}]))),t}function mt(e){return e.replace(dt,`~`)}function ht(e){let t=e.split(`
4
- `).map(e=>e.trim()).filter(e=>e.length>0),n=t[0]??``;return t.length>1?`${n} ${ot} +${t.length-1} lines`:n}function gt(e,t=ct){if(e.length<=t)return e;let n=t-3,r=Math.ceil(n/2),i=e.slice(0,r),a=e.slice(e.length-(n-r)),o=i.lastIndexOf(` `);o>i.length/2&&(i=i.slice(0,o));let s=a.indexOf(` `);return s>=0&&s<a.length/2&&(a=a.slice(s+1)),`${i}${st}${a}`}function _t(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>typeof e==`string`)?e.join(`
5
-
6
- `):``}function vt(e){let t=_t(e);if(t.length===0)return``;let n=Array.isArray(e)?_t(e[0]):t,r=Array.isArray(e)&&e.length>1?` ${ot} +${e.length-1} commands`:``;return gt(`${mt(ht(n))}${r}`)}function yt(e){let t=[];return e.background===!0&&t.push(`bg`),e.interactive===!0&&t.push(`tty`),typeof e.timeout==`number`&&t.push(`${e.timeout}s`),typeof e.name==`string`&&e.name.length>0&&t.push(e.name),t}function bt(e){return e<Q?`${e} B`:e<ut?`${(e/Q).toFixed(1)} KB`:`${(e/ut).toFixed(1)} MB`}function xt(e){let t=[];return e.lines!==void 0&&t.push(`${e.lines.toLocaleString(`en-US`)} lines`),e.fileSize!==void 0&&t.push(bt(e.fileSize)),e.runner!==void 0&&t.push(e.runner),t.join(` · `)}function St(e,t){let n=e.split(`
7
- `);for(;n.length>0&&n[n.length-1]?.trim()===``;)n.pop();return n.length<=t?n:n.slice(-t)}function Ct(e){let t=pt(e.details),n=(t.stages??[]).flatMap(e=>e.logPath===void 0?[]:[`stage ${e.index+1} · ${e.state} · ${e.logPath}`]);if(e.isPartial)return{lines:[...n,...St(e.output,lt)],status:{glyph:`◐`,tone:`running`,text:`running`},hidden:0};if(e.isError){let r=St(t.sequenceId===void 0?e.output:t.tail??e.output,2**53-1),i=[...n,...e.expanded?r:r.slice(-12)],a=xt(t);return{lines:i,status:{glyph:`✗`,tone:`error`,text:a.length>0?a:`failed`},hidden:Math.max(0,r.length+n.length-i.length)}}if(t.promoted===!0)return{lines:n,status:{glyph:`●`,tone:`background`,text:`${t.runner??t.id??`runner`}${t.id===void 0?``:` · ${t.id}`} · background`},hidden:0};let r=St(t.tail??(t.sequenceId===void 0?``:e.output),2**53-1),i=[...n,...e.expanded?r:r.slice(-12)],a=t.exitCode!==void 0&&t.exitCode!==null,o=t.timedOut===!0||a&&t.exitCode!==0,s=[];t.timedOut===!0?s.push(`timed out`):o&&s.push(`exit ${t.exitCode}`);let c=xt(t);c.length>0&&s.push(c);let l=s.length>0?s.join(` · `):o?`failed`:i.length===0?`done`:``;return{lines:i,status:l.length>0?{glyph:o?`✗`:`✓`,tone:o?`error`:`ok`,text:l}:null,hidden:Math.max(0,r.length+n.length-i.length)}}function wt(e){if(e===void 0)return{tone:`info`,badge:`In background`};if(e.exit===void 0)return{tone:`running`,badge:`In background`};let{reason:t,code:n}=e.exit,r=n===null?``:` · exit ${n}`;return t===`completed`?{tone:`ok`,badge:`Completed${r}`}:t===`stopped`?{tone:`neutral`,badge:`Stopped`}:{tone:`error`,badge:`Failed${r}`}}var Tt={running:`running`,ok:`ok`,error:`error`,background:`info`};function Et({sessionId:t,args:r,result:i,output:a,running:o,isError:s,sendSessionFrame:l,openTransientTab:f}){let m=pt(i?.details),h=m.sequenceId===void 0?m.id:void 0,g=m.promoted===!0?h:void 0,_=E(U.store,e=>h===void 0?void 0:U.select(e,t).runs.find(e=>e.id===h)),y=E(U.store,e=>g!==void 0&&U.select(e,t).stopRequested.includes(g)),b=_t(r.command),x=vt(r.command),S=yt(r),C=t!==null&&g!==void 0&&_!==void 0&&_.exit===void 0,w=g===void 0?void 0:wt(_);return j(e,{tone:w?.tone??p({running:o,isError:s}),expandable:!0,children:({expanded:e})=>{let r=Ct({details:i?.details,output:a,expanded:!0,isPartial:o,isError:s});return P(v,{children:[P(c,{title:`bash`,...w?{badge:w.badge}:{},children:[P(`span`,{"data-testid":`tool-call-bash`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[j(`span`,{className:`min-w-0 flex-1 truncate font-mono text-po-text`,children:x}),S.length>0?P(`span`,{className:`hidden shrink-0 text-po-dim sm:inline`,children:[`· `,S.join(` · `)]}):null]}),_!==void 0&&t!==null?P(d,{variant:`outline`,size:`xs`,"data-testid":`tool-result-bash-open-log`,title:`open this runner's full log`,onClick:e=>{e.stopPropagation(),f(Pe(_))},className:`shrink-0 gap-1 px-1.5 `,children:[j(ee,{className:`h-2.5 w-2.5`}),`log`]}):null,C?j(d,{size:`xs`,variant:y?`outline`:`danger-outline`,disabled:y,"data-testid":`tool-result-bash-stop`,"data-stopping":y,title:y?`stop requested; the runner reports its own exit`:`ask the runtime to stop this runner`,onClick:e=>{e.stopPropagation(),t!==null&&g!==void 0&&q(l,t,g)},className:`shrink-0 px-1.5 `,children:y?`stopping…`:`stop`}):null]}),e?P(D,{"data-testid":`tool-result-bash`,className:`flex flex-col gap-2`,children:[b.length>0?j(n,{"data-testid":`tool-result-bash-command`,grammar:`shell`,text:b,className:`max-h-40 overflow-auto text-po-text`}):null,r.lines.length>0?j(ie,{"data-testid":`tool-result-bash-output`,text:r.lines.join(`
8
- `),className:`max-h-96 overflow-auto whitespace-pre-wrap break-words [overflow-wrap:anywhere] border-po-border-soft border-t pt-2 font-mono text-po-dim`}):null,r.status?j(u,{"data-testid":`tool-result-bash-status`,tone:Tt[r.status.tone],glyph:r.status.glyph,className:`min-w-0`,children:j(`span`,{className:`break-words`,children:r.status.text})}):null,m.sequenceId===void 0&&m.logPath!==void 0?P(`span`,{"data-testid":`tool-result-bash-log`,className:`min-w-0 break-all text-po-dim`,children:[`full log · `,j(`span`,{className:`text-po-dim`,children:m.logPath})]}):null]}):null]})}})}var Dt=l({message:Et}),$=(e,t)=>t===void 0?void 0:{...e,...t},Ot=i({id:`runner`,session:{get activityGroups(){return[$({name:`runners`},Qe)]},get channels(){return[$({channel:`runner_runs`},$e)]},get fills(){return[$({slot:`activity.runners`,id:`runners`},at)]},get toolRenderers(){return[$({tools:[`bash`]},Dt)]}}});export{Ot as webPlugin};
@@ -1 +0,0 @@
1
- import{Bn as e,Fn as t,Fr as n,I as r,In as i,Jt as a,Ln as o,Pn as s,Pr as c,Qt as l,R as u,Rn as d,Sr as f,Un as p,V as m,ct as h,d as g,g as _,o as v,s as y,xr as b,zn as x}from"../chunks/po-web-runtime-DtS_FP_f.js";function S(e,t){return e.flatMap(e=>{try{let n=e.localSessionId?.(t.from)??t.from,r=e.localSessionId?.(t.to)??t.to;return n!==t.from||(e.qualifySessionId?.(t.from)??t.from)===t.from?[{runtime:e,from:n,to:r}]:[]}catch{return[]}}).at(-1)}async function C(e,t){let n=S(e,t);if(!n)return`Po is not connected. Your text is kept; try again.`;try{await n.runtime.invokeServerMethod({mount:{scope:`host`},service:`sessions`,method:`sendToSession`,input:{from:n.from,to:n.to,text:t.text}});return}catch(e){return e instanceof Error&&e.message!==``?e.message:`The message was not delivered.`}}var w=f(void 0),T=f([]);function E(e){return T.update(t=>[...t,e]),()=>T.update(t=>t.filter(t=>t!==e))}function D(e){w.update(()=>({text:e}))}function O(e){let t=()=>{let t=w.store.state;t&&(w.reset(),e(t))},n=w.store.subscribe(t);return t(),()=>n.unsubscribe()}function k(e){return C(T.store.state,e)}function A({takeComposerDraft:e,listSessions:t}){return!e||!t?null:y(u,{role:`menuitem`,density:`compact`,"data-testid":`composer-menu-send-to-session`,className:`w-full text-po-text hover:bg-po-tint-blue`,onClick:()=>D(e()),children:[v(h,{"aria-hidden":!0,className:`h-3 w-3 shrink-0`}),v(r,{density:`compact`,children:`Send to session…`})]})}var j=b({component:A}),M={running:`green`,waiting:`magenta`,idle:`neutral`};function N({open:n,sessions:r,to:c,text:u,error:f,sending:g,onPick:_,onTextChange:b,onCancel:S,onSend:C}){let w=r.find(e=>e.id===c);return v(s,{open:n,onOpenChange:e=>e?void 0:S(),children:y(i,{width:`md`,"data-testid":`send-to-session-dialog`,children:[v(x,{children:v(e,{children:`Send to session`})}),y(t,{className:`flex flex-col gap-3`,children:[v(o,{children:`It reaches that session right away, in its current turn, as a message from you.`}),r.length===0?v(`p`,{className:`text-sm text-po-dim`,children:`No other session is running. Open one, then send.`}):v(m,{label:`Sessions`,items:r.map(e=>({value:e.id,title:e.name,subtitle:e.detail,lead:v(p,{tone:M[e.state],size:`md`})})),value:c===void 0?[]:[c],filterable:!0,filterPlaceholder:`Search sessions`,onSelect:_,className:`max-h-56 rounded-md border border-po-border`}),v(a,{"aria-label":`Message`,rows:3,value:u,"data-testid":`send-to-session-text`,onChange:e=>b(e.currentTarget.value)}),f===``?null:v(`p`,{role:`alert`,className:`text-sm text-po-red`,children:f}),y(d,{children:[v(l,{variant:`outline`,size:`md`,onClick:S,children:`Cancel`}),y(l,{variant:`primary`,size:`md`,className:`gap-1.5`,"data-testid":`send-to-session-send`,disabled:w===void 0||u.trim()===``||g,onClick:C,children:[v(h,{"aria-hidden":!0,className:`size-3.5`}),w===void 0?`Send`:`Send to ${w.name}`]})]})]})]})})}function P({sessionId:e,listSessions:t,appendComposerDraft:n}){let[r,i]=_(!1),[a,o]=_([]),[s,c]=_(void 0),[l,u]=_(``),[d,f]=_(``),[p,m]=_(!1);if(g(()=>O(e=>{o(t?.()??[]),c(void 0),u(e.text),f(``),i(!0)}),[t]),!r||e===null)return null;let h=()=>{p||(n(l),i(!1))},y=async()=>{if(s===void 0)return;m(!0);let t=await k({from:e,to:s,text:l.trim()});m(!1),t===void 0?i(!1):f(t)};return v(N,{open:!0,sessions:a,to:s,text:l,error:d,sending:p,onPick:c,onTextChange:u,onCancel:h,onSend:()=>void y()})}var F=b({component:P}),I=c(E),L=(e,t)=>t===void 0?void 0:{...e,...t},R=n({id:`sessions`,session:{get fills(){return[L({slot:`composer-menu`,id:`send-to-session`},j),L({slot:`overlay`,id:`send-to-session-dialog`},F)]},get start(){return I}}});export{R as webPlugin};
@@ -1,7 +0,0 @@
1
- import{$n as e,$t as t,A as n,Ar as r,At as i,Bn as a,Cr as o,Dr as s,Et as c,Fr as l,Gn as u,In as d,It as f,Jt as p,Kn as m,Ln as h,Lr as g,M as _,Mr as v,N as y,Ot as b,Pn as x,Qt as S,Rn as ee,Rr as te,Sn as ne,Tt as re,Un as ie,Vn as C,Wn as ae,Zn as w,_r as oe,a as T,an as E,at as se,bn as D,ct as ce,d as O,dt as k,et as A,f as j,fr as le,g as M,h as ue,hr as de,i as N,it as fe,j as pe,jr as me,k as he,kr as ge,n as _e,o as P,ot as ve,rt as ye,s as F,st as be,vr as xe,wt as Se,x as Ce,xr as we,z as Te,zn as Ee}from"../chunks/po-web-runtime-DtS_FP_f.js";var De={id:`team`,label:`Team`,detail:`subagent defaults for new sessions, used only where agent frontmatter is unset. existing overrides still apply.`,order:50,fields:[{id:`model`,label:`default model`,keyPath:[`subagents`,`model`],placeholder:`inherit existing defaults`,detail:`model used when the agent frontmatter does not set one.`,models:!0},{id:`thinking`,label:`default thinking`,keyPath:[`subagents`,`thinking`],placeholder:`inherit`,detail:`thinking level used when the agent frontmatter does not set one. off disables thinking by default.`,options:[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]},{id:`fallbackModels`,label:`fallback models`,keyPath:[`subagents`,`fallbackModels`],placeholder:`provider/model:thinking, provider/model`,detail:`comma-separated model specs, tried in order. each may include a :thinking suffix.`},{id:`excludeTools`,label:`excluded tools`,keyPath:[`subagents`,`excludeTools`],placeholder:`tool-one, tool-two`,detail:`comma-separated tool names added to the layer exclusions. existing restrictions still apply.`}].map(e=>({id:e.id,label:e.label,kind:e.models===!0||e.options!==void 0?`select`:`text`,keyPath:e.keyPath,detail:e.detail,placeholder:e.placeholder,...e.models===!0?{optionsFrom:`models`}:{},...e.options===void 0?{}:{options:e.options.map(e=>({value:e,label:e}))}}))},Oe=ge({...De,icon:t}),ke=ge({...De,icon:t}),Ae=`subagent_runs`,je=`subagent_catalog`;function I(e,t){return g(te(e),`team`,t)}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function R(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Me(e){return L(e)&&typeof e.name==`string`&&typeof e.description==`string`&&typeof e.filePath==`string`&&[`project`,`user`,`plugin`].includes(String(e.source))&&(e.packageName===void 0||typeof e.packageName==`string`)&&(e.model===void 0||typeof e.model==`string`)&&R(e.fallbackModels)&&R(e.tools)&&R(e.skills)&&R(e.extensions)&&(e.defaultContext===`fresh`||e.defaultContext===`fork`)}async function Ne(e,t){let n=await _e.fetch(I(e,`/catalog`),{signal:t,cache:`no-store`}),r=await n.json();if(!n.ok)throw Error(L(r)&&typeof r.error==`string`?r.error:`Agent catalog could not be loaded (${n.status}).`);if(!L(r)||typeof r.cwd!=`string`||!Array.isArray(r.agents)||!r.agents.every(Me)||!R(r.models))throw Error(`The server returned an invalid agent catalog.`);return{cwd:r.cwd,agents:r.agents,models:r.models}}async function Pe(e,t){let n=await _e.fetch(I(e,`/run`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await n.json();if(!n.ok)throw Error(L(r)&&typeof r.error==`string`?r.error:`Agent could not be launched (${n.status}).`);if(!L(r)||typeof r.runId!=`string`||r.runId===``)throw Error(`The server returned an invalid run ID.`);return r.runId}function Fe(e){return e===`delivered`||e===`failed`||e===`pending`}async function Ie(e,t,n){let r=await _e.fetch(I(e,`/steer`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({runId:t,message:n})}),i=await r.json();if(!r.ok)throw Error(L(i)&&typeof i.error==`string`?i.error:`Guidance could not be sent (${r.status}).`);if(!L(i)||!Fe(i.state)||typeof i.message!=`string`)throw Error(`The server returned an invalid steer result.`);return{state:i.state,message:i.message}}async function Le(e,t){let n=await _e.fetch(I(e,`/stop`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({runId:t})}),r=await n.json();if(!n.ok)throw Error(L(r)&&typeof r.error==`string`?r.error:`The run could not be stopped (${n.status}).`)}var z=s({cwd:``,agents:[],models:[],warning:void 0,loading:!1,requestId:0,open:!1,filter:``,task:``,selected:void 0,inspected:void 0,launch:void 0});function Re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function B(e,t=``){z.update(e,e=>({...e,open:!0,task:t}))}function ze(e,t){e.sessionId!==null&&(B(e.sessionId,e.item.content),e.openTransientTab(t()))}function V(e){z.update(e,e=>({...e,open:!1,task:``,launch:void 0}))}function Be(e){let t=new AbortController,n=z.select(z.store.state,e).requestId+1;z.update(e,e=>({...e,requestId:n,loading:!0,warning:void 0}));let r=()=>!t.signal.aborted&&z.store.state[e]?.requestId===n;return Ne(e,t.signal).then(t=>{r()&&Ve.apply(e,t)}).catch(t=>{r()&&z.update(e,e=>({...e,warning:t instanceof Error?t.message:String(t)}))}).finally(()=>{r()&&z.update(e,e=>({...e,loading:!1}))}),()=>{r()&&z.update(e,e=>({...e,loading:!1})),t.abort()}}var Ve=z.channel({channel:je,parse(e){if(!Re(e)||typeof e.cwd!=`string`||!Array.isArray(e.agents))return null;let t=Array.isArray(e.models)?e.models.filter(e=>typeof e==`string`):[];return{cwd:e.cwd,agents:e.agents.filter(Re),models:t,...typeof e.warning==`string`?{warning:e.warning}:{}}},reduce(e,t){let n=new Set(t.agents.map(e=>e.name));return{...e,cwd:t.cwd,agents:t.agents,models:t.models,warning:t.warning,selected:e.selected!==void 0&&n.has(e.selected)?e.selected:void 0,inspected:e.inspected!==void 0&&n.has(e.inspected)?e.inspected:void 0,launch:e.launch!==void 0&&n.has(e.launch.agent)?e.launch:void 0}}}),He=6e4,Ue=60*He;function We(e){if(e<He)return`<1m`;if(e<Ue)return`${Math.floor(e/He)}m`;let t=Math.floor(e/Ue),n=Math.floor(e%Ue/He);return`${t}h ${String(n).padStart(2,`0`)}m`}function Ge(e){let t=/^\/(?:Users|home)\/[^/]+/u.exec(e);return t?`~${e.slice(t[0].length)}`:e}function Ke(e){return H(e).name}function qe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(e){let t=e.identity?.split(`-`)[0];return!e.identity||!t?{name:e.agent,role:``,seed:e.agent}:{name:qe(t),role:e.agent,seed:e.identity}}var Je=r({slot:`subagents.run-actions`}),Ye=new Set([`done`,`failed`,`stopped`]);function U(e){return Ye.has(e.state)}var W=s({runs:[],dismissed:[],stopRequested:[],openRunId:void 0,pendingLaunch:void 0,autoOpenRunId:void 0});function Xe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ze(e,t){return e.filter(e=>e!==t)}function Qe(e){return e.runs.filter(t=>!e.dismissed.includes(t.runId)).sort((e,t)=>Number(U(e))-Number(U(t)))}function $e(e){return Qe(e).filter(e=>e.state===`queued`||e.state===`running`)}async function et(e,t){W.update(e,e=>({...e,stopRequested:[...Ze(e.stopRequested,t),t]}));try{await Le(e,t)}catch(n){throw W.update(e,e=>({...e,stopRequested:Ze(e.stopRequested,t)})),n}}function tt(e,t){W.update(e,e=>({...e,dismissed:[...Ze(e.dismissed,t),t],openRunId:e.openRunId===t?void 0:e.openRunId}))}function nt(e,t){W.update(e,e=>({...e,pendingLaunch:{agent:t,knownRunIds:e.runs.map(e=>e.runId)}}))}function rt(e){W.update(e,e=>({...e,pendingLaunch:void 0}))}function it(e){W.update(e,e=>({...e,autoOpenRunId:void 0}))}function at(e,t){W.update(e,e=>({...e,openRunId:t}))}var ot=W.channel({channel:Ae,parse(e){return!Xe(e)||!Array.isArray(e.runs)?null:{runs:e.runs.filter(Xe)}},reduce(e,{runs:t}){let n=new Map(t.map(e=>[e.runId,e])),r=e.stopRequested.filter(e=>{let t=n.get(e);return t!==void 0&&!U(t)}),i=e.dismissed.filter(e=>n.has(e)),a=e.pendingLaunch===void 0?void 0:t.find(t=>t.agent===e.pendingLaunch?.agent&&!e.pendingLaunch.knownRunIds.includes(t.runId));return{...e,runs:t,stopRequested:r,dismissed:i,pendingLaunch:a===void 0?e.pendingLaunch:void 0,autoOpenRunId:a===void 0?e.autoOpenRunId:a.runId}}});function st(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>[e.name,e.source,e.packageName??``,e.description,...e.tools].some(e=>e.toLowerCase().includes(n)))}function ct(e,t){let n=new Set,r=[];for(let i of[e.model??``,...e.fallbackModels,...t])i===``||n.has(i)||(n.add(i),r.push(i));return r}var lt={project:`Project`,user:`User`,plugin:`Package`};function ut({label:e,value:t,onChange:n,options:r,disabled:i}){return F(ye,{disabled:i,value:t,onValueChange:n,children:[P(ve,{"aria-label":e,className:`h-9 w-full`,children:P(be,{})}),P(fe,{children:r.map(([e,t])=>P(se,{value:e,children:t},e))})]})}function dt({agents:e,models:t,initialSearch:n=``,initialSelected:r,initialTask:i=``,initialFork:o,loading:s=!1,warning:c,cwd:l=``,catalogNote:u,runNote:f,onClose:m,onLaunch:g,onSource:_}){let[v,y]=M(n),[b,x]=M(`all`),[te,ne]=M(r),[re,ie]=M(i),[C,ae]=M(o===void 0?void 0:o?`fork`:`fresh`),[w,oe]=M(`default`),[E,se]=M(!1),D=ue(!1),[ce,O]=M(),A=st(e,v).filter(e=>b===`all`||e.source===b),j=te===void 0?A[0]:A.find(e=>e.name===te),de=C??j?.defaultContext??`fresh`,N=e=>{ne(e.name),ae(e.defaultContext),oe(`default`),O(void 0)},fe=async()=>{if(!(!j||s||D.current)){D.current=!0,se(!0),O(void 0);try{await g({agent:j.name,task:re,fork:de===`fork`,...w==="default"?{}:{model:w}})}catch(e){O(e instanceof Error?e.message:String(e))}finally{D.current=!1,se(!1)}}},pe=w==="default"?j?.model??`Runtime default`:w,me=de===`fresh`?`Fresh context`:`This conversation`;return F(d,{"data-testid":`launch-dialog`,className:`w-6xl`,"aria-describedby":`launcher-description`,children:[P(Ee,{dismissible:!0,closeLabel:`Close new agent run`,className:`p-6 sm:px-6`,children:F(`div`,{className:`space-y-1`,children:[P(a,{children:`New agent run`}),P(h,{id:`launcher-description`,children:`Choose an agent, review its setup, then give it a task.`})]})}),F(`div`,{className:`grid min-h-0 overflow-y-auto md:grid-cols-3`,children:[F(`aside`,{"aria-label":`Agent catalog`,onKeyDown:e=>{if(!(E||e.target.getAttribute(`role`)===`combobox`)){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let t=A.findIndex(e=>e.name===j?.name),n=A[(t+(e.key===`ArrowDown`?1:-1)+A.length)%A.length];n&&N(n)}if(e.target.tagName!==`INPUT`&&(e.key===`f`&&ae(`fork`),e.key===`i`)){let t=e.currentTarget.parentElement?.querySelector(`details`);t&&(t.open=!t.open)}}},className:`flex flex-col gap-3 border-b border-po-border p-5 md:border-r md:border-b-0`,children:[P(le,{autoFocus:!0,"data-testid":`catalog-filter`,disabled:E,"aria-label":`Find an agent`,placeholder:`Find an agent…`,value:v,onChange:e=>y(e.target.value)}),P(ut,{disabled:E,label:`Source filter`,value:b,onChange:x,options:[[`all`,`All sources`],[`project`,`Project`],[`user`,`User`],[`plugin`,`Package`]]}),F(`div`,{className:`flex flex-col gap-1 py-2`,children:[s?P(`p`,{role:`status`,className:`text-sm text-po-dim`,children:`Loading agents…`}):null,c?P(`p`,{role:`alert`,className:`text-sm text-po-red`,children:c}):null,A.map(e=>F(S,{variant:`ghost`,size:`card`,"aria-pressed":j?.name===e.name,className:j?.name===e.name?`border-l-4 border-po-green bg-po-selected/15`:`border-l-4 border-transparent`,disabled:E,onClick:()=>{N(e)},children:[P(`span`,{className:`font-semibold text-po-hi`,children:e.name}),P(`span`,{className:`text-sm text-po-dim`,children:e.description.split(`.`)[0]}),F(`span`,{className:`text-sm text-po-dim`,children:[lt[e.source],` · `,e.model??`Default model`]})]},e.name)),A.length===0&&!s?F(`div`,{className:`space-y-3 py-6`,children:[P(`p`,{className:`text-base text-po-hi`,children:`No matching agents`}),P(`p`,{className:`text-sm text-po-dim`,children:`Try another name or source.`}),P(S,{onClick:()=>{y(``),x(`all`)},children:`Clear filters`})]}):null]}),F(`p`,{className:`mt-auto text-sm text-po-dim`,children:[A.length,` agents`,u?` · ${u}`:``]})]}),P(`section`,{className:`space-y-5 p-6 md:col-span-2`,"aria-label":`Agent definition and run`,children:j?F(T,{children:[F(`div`,{className:`space-y-2`,children:[P(`p`,{className:`text-sm text-po-dim`,children:`Agent definition`}),F(`div`,{className:`flex items-center gap-3`,children:[P(`h2`,{className:`text-2xl font-semibold text-po-hi`,children:j.name}),P(k,{children:lt[j.source]})]}),P(`p`,{className:`text-base text-po-text`,children:j.description}),P(`p`,{className:`break-all font-mono text-sm text-po-dim`,children:_?.(j)?P(`button`,{type:`button`,className:`text-left text-po-green underline`,onClick:_(j),children:j.filePath}):j.filePath}),j.packageName?P(`p`,{className:`text-sm text-po-dim`,children:j.packageName}):null,F(`details`,{className:`text-base text-po-text`,children:[P(`summary`,{className:`cursor-pointer text-po-green`,children:`View instructions`}),P(`p`,{className:`mt-2 whitespace-pre-wrap rounded-md bg-po-deep p-3 text-sm`,children:_?.(j)?P(S,{variant:`link`,onClick:_(j),children:`Open source instructions`}):`Instructions stay in the source definition. File viewing is not available in this host.`})]})]}),P(`dl`,{className:`grid gap-x-6 gap-y-3 text-base sm:grid-cols-2`,children:[[`Model`,j.model??`Runtime default`],[`Tools`,j.tools.length?j.tools.join(` · `):`All session tools (not narrowed)`],[`Fallback models`,j.fallbackModels.join(` · `)||`None specified`],[`Skills`,j.skills.join(` · `)||`None specified`],[`Default context`,j.defaultContext===`fresh`?`Fresh`:`This conversation`],[`Extensions`,j.extensions.join(` · `)||`None specified`]].map(([e,t])=>F(`div`,{className:`space-y-1`,children:[P(`dt`,{className:`text-sm text-po-dim`,children:e}),P(`dd`,{className:`break-words text-po-text`,children:t})]},e))}),F(`div`,{className:`space-y-3 border-t border-po-border pt-4`,children:[P(`h3`,{className:`text-lg font-semibold text-po-hi`,children:`This run`}),F(`label`,{className:`flex flex-col gap-1 text-base text-po-text`,children:[`Task`,P(p,{"data-testid":`launch-task`,disabled:E,placeholder:`What should the agent do? Leave empty to use its own prompt.`,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&(e.preventDefault(),fe())},rows:3,value:re,onChange:e=>{ie(e.target.value),O(void 0)}})]}),F(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[F(`div`,{className:`space-y-1`,children:[P(`p`,{className:`text-base text-po-text`,children:`Context`}),P(ut,{disabled:E,label:`Context`,value:de,onChange:ae,options:[[`fresh`,`Fresh context`],[`fork`,`This conversation`]]}),P(`p`,{className:`text-sm text-po-dim`,children:`Start clean, or include this conversation.`})]}),F(`div`,{className:`space-y-1`,children:[P(`p`,{className:`text-base text-po-text`,children:`Model override`}),P(ut,{disabled:E,label:`Model override`,value:w,onChange:oe,options:[[`default`,`Use agent default`],...ct(j,t).map(e=>[e,e])]}),P(`p`,{className:`text-sm text-po-dim`,children:`Changes apply only to this run.`})]})]})]})]}):P(`p`,{className:`py-12 text-base text-po-dim`,children:`Choose an agent to review its definition. Clear the filters if no agents match.`})})]}),F(ee,{variant:`bar`,className:`gap-3 p-4 sm:px-6 sm:py-4`,children:[F(`div`,{className:`min-w-0 flex-1 space-y-1 text-sm text-po-dim`,children:[P(`p`,{className:`break-words`,children:j?`${j.name} · ${me} · ${pe}`:`No agent selected`}),P(`p`,{role:`status`,children:f??`Enter starts the run · Shift+Enter for a new line${l?` · ${l}`:``}`}),ce?P(`p`,{role:`alert`,className:`text-po-red`,children:ce}):null]}),P(S,{"data-testid":`launch-cancel`,onClick:m,children:`Cancel`}),P(S,{"data-testid":`launch-submit`,variant:`primary`,disabled:!j||E||s,onClick:()=>void fe(),children:E?`Starting…`:`Start run`})]})]})}function ft({sessionId:e,agent:t,agents:n,loading:r,warning:i,onSource:a,cwd:o,models:s,fork:c,initialTask:l,onClose:u,onLaunched:d}){return P(x,{open:!0,onOpenChange:e=>{e||u()},children:P(dt,{agents:n??(t?[t]:[]),models:s,initialSelected:t?.name,initialTask:l,initialFork:c,loading:r,warning:i,cwd:o,onSource:a,onClose:u,onLaunch:async t=>{nt(e,t.agent);try{await Pe(e,t),d()}catch(t){throw rt(e),t}}})})}function pt({sessionId:e,onClose:t,onSource:n}){let r=N(z.store,t=>z.select(t,e));return P(ft,{sessionId:e,agents:r.agents,agent:r.agents.find(e=>e.name===(r.launch?.agent??r.selected)),cwd:r.cwd,models:r.models,fork:r.launch?.fork,initialTask:r.task,loading:r.loading,warning:r.warning,onSource:n,onClose:t,onLaunched:t})}var mt={queued:{label:`QUEUED`,tone:`neutral`},running:{label:`RUNNING`,tone:`running`},done:{label:`DONE`,tone:`ok`},failed:{label:`FAILED`,tone:`error`},stopped:{label:`STOPPED`,tone:`neutral`}};function ht(e,t){let n=e.endedAt??(e.state===`running`||e.state===`queued`?t:e.lastUpdate);return We(Math.max(0,n-e.startedAt))}function G({run:e}){let t=ue(null),[n]=M(Date.now);return O(()=>{let n,r=()=>{let i=t.current?.firstChild,a=Date.now();i&&(i.nodeValue=ht(e,a)),!U(e)&&e.endedAt===void 0&&(n=setTimeout(r,6e4-Math.max(0,a-e.startedAt)%6e4))};return r(),()=>clearTimeout(n)},[e]),P(`span`,{ref:t,children:ht(e,n)})}function gt({sessionId:e,run:t,stopping:n}){let[r,i]=M(),a=(e,t)=>{e.stopPropagation(),t()},o=()=>{i(void 0),et(e,t.runId).catch(e=>i(e instanceof Error?e.message:String(e)))};return U(t)?P(S,{variant:`outline`,size:`xs`,"data-testid":`run-clear-${t.runId}`,title:`clear this run from the grid`,onClick:n=>a(n,()=>tt(e,t.runId)),children:`clear`}):F(T,{children:[r?P(`span`,{role:`alert`,"data-testid":`run-stop-error-${t.runId}`,title:r,className:`min-w-0 truncate text-sm text-po-red`,children:r}):null,P(S,{variant:n?`outline`:`danger-outline`,size:`xs`,"data-testid":`run-stop-${t.runId}`,"data-stopping":n,disabled:n,title:n?`stop requested; the run reports its own final state`:`ask the runtime to stop this run`,onClick:e=>a(e,o),children:n?`stopping…`:`stop`})]})}var K=`Not reported`,_t={done:`This run has finished. Start a new run from Agents.`,failed:`This run failed. Start a new run from Agents.`,stopped:`This run was stopped. Start a new run from Agents.`};function q({label:e,children:t}){return F(`div`,{className:`flex gap-3`,children:[P(`span`,{className:`w-24 shrink-0 text-sm text-po-dim`,children:e}),P(`div`,{className:`min-w-0 flex-1 break-words text-base text-po-text`,children:t})]})}function vt({run:e}){let t=[e?.toolCount===void 0?void 0:`${e.toolCount} tools`,e?.tokens===void 0?void 0:`${e.tokens.toLocaleString()} tokens`].filter(Boolean).join(` · `);return F(T,{children:[F(q,{label:`Agent`,children:[P(`span`,{className:`font-semibold text-po-hi`,children:e?.agent??K}),e?.agentDescription?P(`p`,{className:`text-po-dim`,children:e.agentDescription}):null,e?.agentFilePath?P(`p`,{className:`font-mono text-sm text-po-dim`,children:e.agentFilePath}):null]}),F(q,{label:`Model`,children:[e?.model??K,e?.model&&e.modelSource===`configured`?P(`span`,{className:`text-po-dim`,children:` · configured, not confirmed by the runtime`}):null]}),P(q,{label:`Thinking`,children:P(`span`,{className:`capitalize`,children:e?.thinking??K})}),P(q,{label:`Prompt`,children:e?.promptWithheld?P(`span`,{className:`text-po-dim`,children:`Withheld: this task was marked sensitive.`}):P(`pre`,{className:`max-h-40 overflow-y-auto rounded-md bg-po-deep px-3 py-2 font-sans whitespace-pre-wrap break-words`,children:e?.task||K})}),e?.taskRef?P(q,{label:`Task`,children:P(k,{tone:`violet`,size:`xs`,className:`rounded-sm bg-po-violet/10`,children:e.taskRef})}):null,P(q,{label:`Folder`,children:P(`span`,{className:`font-mono text-sm`,children:e?.cwd?Ge(e.cwd):K})}),P(q,{label:`Usage`,children:P(`span`,{className:`text-po-dim`,children:t||K})})]})}function yt({run:e,gone:t,elapsed:n,stopControl:r,thread:i,canSteer:a,stopping:o,guidance:s,sending:c,error:l,notice:u,onGuidanceChange:d,onSubmit:m,initialInfoOpen:h=!1}){let[g,_]=M(h),v=j(),y=e?mt[e.state]:void 0,b={variant:`outline`,size:`md`,className:`min-w-0 max-w-full gap-2`,"aria-expanded":g,"aria-controls":v,onClick:()=>_(e=>!e)},x=e&&U(e)?_t[e.state]:e?.canSteer===!1&&!t?`This runtime does not take guidance while it runs.`:`Guidance is unavailable for this run.`;return F(`div`,{"data-testid":`agent-thread-panel`,className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-po-bg`,children:[F(`div`,{"data-testid":`agent-thread-header`,className:`flex h-11 shrink-0 items-center gap-2.5 border-b border-po-border-soft bg-po-rail px-[26px]`,children:[e?P(C,{name:H(e).name,seed:H(e).seed,size:`sm`}):null,P(`span`,{"data-testid":`agent-thread-agent`,className:`min-w-0 shrink truncate text-base font-semibold text-po-hi`,children:e?Ke(e):`Agent run`}),e&&H(e).role?P(`span`,{className:`min-w-0 shrink truncate text-sm text-po-dim`,children:H(e).role}):null,y?P(f,{tone:y.tone,"data-testid":`agent-thread-state`,className:`shrink-0`,children:o&&e&&!U(e)?`STOPPING…`:y.label}):null,P(`span`,{className:`min-w-0 flex-1 truncate text-sm text-po-dim`,children:n}),r]}),t?P(`div`,{"data-testid":`agent-thread-gone`,className:`shrink-0 border-b border-po-border-soft px-[26px] py-2 text-sm text-po-dim`,children:`This run is no longer listed. Its thread stays readable.`}):null,P(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:i}),P(`section`,{id:v,"aria-label":`Run info`,"data-testid":`run-info`,hidden:!g,className:`mx-[26px] mb-2 flex max-h-[40vh] shrink-0 flex-col gap-3 overflow-y-auto rounded-lg border border-po-border bg-po-panel px-4 py-3`,children:P(vt,{run:e})}),a?P(`form`,{"data-testid":`agent-steer-composer`,className:`shrink-0 px-[26px] pt-2 pb-2`,onSubmit:e=>{e.preventDefault(),m()},children:F(`div`,{className:`rounded-lg border border-po-border bg-po-panel transition-colors focus-within:border-po-blue/60`,children:[P(p,{variant:`bare`,"data-testid":`agent-steer-input`,"aria-label":`Steering guidance`,rows:2,value:s,readOnly:c,disabled:o,placeholder:o?`Stopping, guidance paused`:`Guide this agent · it reads this at its next step`,className:`w-full px-4 pt-3 text-lg leading-relaxed`,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key!==`Enter`||e.shiftKey||e.nativeEvent.isComposing||(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}),l?P(`p`,{role:`alert`,"data-testid":`agent-steer-error`,className:`px-4 pt-1 text-sm text-po-red`,children:l}):null,F(`div`,{className:`flex items-center gap-3 px-4 pt-1 pb-3`,children:[P(`span`,{className:`min-w-0 flex-1`}),P(`span`,{role:`status`,"data-testid":`agent-steer-hint`,title:u,className:`min-w-0 truncate text-sm text-po-dim`,children:u??`Shift + Enter for a new line`}),F(S,{"data-testid":`agent-steer-submit`,type:`submit`,variant:`primary`,size:`lg`,className:`shrink-0 gap-2`,disabled:o||c||s.trim()===``,children:[P(ce,{className:`size-4`}),c?`Sending…`:`Send`]})]})]})}):P(`div`,{"data-testid":`agent-thread-end`,className:`shrink-0 px-[26px] pt-3 pb-2 text-sm text-po-dim`,children:x}),F(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2 px-[26px] pb-4`,children:[F(S,{...b,"data-testid":`run-chip-agent`,children:[P(`span`,{"aria-hidden":!0,className:`size-1.5 shrink-0 rounded-full bg-po-magenta`}),P(`span`,{className:`truncate`,children:e?.agent??`Agent`}),P(D,{"aria-hidden":!0,className:`size-3.5 shrink-0`})]}),F(S,{...b,"data-testid":`run-chip-model`,children:[P(`span`,{"aria-hidden":!0,className:`size-1.5 shrink-0 rounded-full bg-po-green`}),P(`span`,{className:`truncate`,children:e?.model?e.model.split(`/`).pop()??e.model:`Model not reported`}),e?.thinking?P(`span`,{className:`shrink-0 text-po-dim`,children:e.thinking}):null,P(D,{"aria-hidden":!0,className:`size-3.5 shrink-0`})]}),F(S,{...b,"data-testid":`run-chip-prompt`,children:[P(`span`,{"aria-hidden":!0,className:`size-1.5 shrink-0 rounded-full bg-po-blue`}),`Prompt`,P(D,{"aria-hidden":!0,className:`size-3.5 shrink-0`})]})]})]})}var bt=`subagents-run-`;function xt(e){let t=e.runId;return{id:`${bt}${t}`,label:Ke(e),panel:e=>P(St,{...e,runId:t},`${e.sessionId}:${t}`)}}function St({sessionId:e,runId:t,renderThread:n}){let{runs:r,stopRequested:i}=N(W.store,t=>W.select(t,e)),a=r.find(e=>e.runId===t),[o,s]=M(a);a!==void 0&&a!==o&&s(a);let c=a??o,l=a===void 0,[u,d]=M(``),[f,p]=M(!1),[m,h]=M(),[g,_]=M(),v=e!==null&&a!==void 0&&!U(a),y=i.includes(t),b=v&&a.canSteer!==!1,x=async()=>{let n=u.trim();if(b&&!y&&n&&!f){p(!0),h(void 0),_(void 0);try{let r=await Ie(e,t,n);if(r.state===`failed`){h(r.message);return}d(``),r.state===`pending`&&_(r.message)}catch(e){h(e instanceof Error?e.message:String(e))}finally{p(!1)}}};return P(yt,{run:c,gone:l,elapsed:c?P(G,{run:l?{...c,endedAt:c.endedAt??c.lastUpdate}:c}):void 0,stopControl:v?P(gt,{sessionId:e,run:a,stopping:y}):void 0,thread:n(t),canSteer:b,stopping:y,guidance:u,sending:f,error:m,notice:g,onGuidanceChange:d,onSubmit:()=>void x()})}var Ct=`subagents-fleet`,wt=8;function Tt({run:e}){let t=e.task.split(`
2
- `).find(e=>e.trim()!==``)??``;return e.taskRef?F(`div`,{className:`flex items-center gap-2 px-3 pb-2.5`,children:[F(k,{tone:`violet`,size:`xs`,className:`shrink-0 rounded-sm bg-po-violet/10`,children:[`TASK `,e.taskRef]}),P(`span`,{"data-testid":`run-work`,className:`min-w-0 truncate text-base text-po-hi`,children:t})]}):F(`div`,{className:`flex items-center gap-2 px-3 pb-2.5`,children:[P(`span`,{className:`shrink-0 text-base font-medium text-po-dim`,children:`Prompt`}),P(`span`,{"data-testid":`run-work`,className:`min-w-0 truncate text-base text-po-dim`,children:t})]})}function Et({sessionId:t,run:n,stopping:r,onOpenThread:i,onOpenDetail:a}){let[o,s]=M();return F(T,{children:[o?P(`span`,{role:`alert`,"data-testid":`run-menu-stop-error-${n.runId}`,title:o,className:`min-w-0 truncate text-sm text-po-red`,children:o}):null,F(ae,{children:[P(e,{asChild:!0,children:P(S,{variant:`ghost`,size:`icon`,"data-testid":`run-menu-${n.runId}`,title:`what this run can do`,"aria-label":`run actions`,onClick:e=>e.stopPropagation(),children:P(Ce,{className:`h-3 w-3`})})}),F(u,{"data-testid":`run-menu-content-${n.runId}`,children:[P(m,{"data-testid":`run-open-${n.runId}`,onSelect:i,children:`open thread`}),P(m,{"data-testid":`run-detail-${n.runId}`,onSelect:a,children:`details`}),P(w,{}),U(n)?P(m,{"data-testid":`run-clear-${n.runId}`,onSelect:()=>tt(t,n.runId),children:`clear from the grid`}):P(m,{variant:`destructive`,"data-testid":`run-stop-${n.runId}`,"data-stopping":r,disabled:r,onSelect:()=>{s(void 0),et(t,n.runId).catch(e=>s(e instanceof Error?e.message:String(e)))},children:r?`stopping…`:`stop`})]})]})]})}function Dt({sessionId:e,run:t,stopping:n,renderThread:r,onOpenThread:i,onOpenDetail:a}){let o=mt[t.state],s=H(t);return P(Te,{asChild:!0,className:E(`flex h-[280px] min-w-0 flex-col text-left transition-colors outline-none hover:border-po-blue/50 focus-within:border-po-blue`,A[o.tone]),children:F(`div`,{"data-testid":`run-card-${t.runId}`,"data-run-state":t.state,children:[F(`div`,{role:`button`,tabIndex:0,"data-testid":`run-open-card-${t.runId}`,className:`flex min-h-0 flex-1 cursor-pointer flex-col outline-none`,title:`open this run's own thread in a tab`,onClick:i,onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())},children:[F(`div`,{className:`flex items-center gap-2 px-3 pt-2.5 pb-1.5`,children:[P(C,{name:s.name,seed:s.seed,size:`sm`}),P(`span`,{"data-testid":`run-agent`,className:`truncate text-base font-semibold text-po-hi`,children:s.name}),s.role?P(`span`,{className:`truncate text-sm text-po-dim`,children:s.role}):null,P(`span`,{className:`min-w-0 flex-1`}),P(`span`,{className:`shrink-0 text-sm text-po-dim`,children:P(G,{run:t})}),P(f,{tone:o.tone,"data-testid":`run-state`,children:o.label})]}),P(Tt,{run:t}),P(`div`,{"data-testid":`run-stream`,className:`pointer-events-none flex min-h-0 flex-1 flex-col overflow-hidden border-t border-po-border-soft bg-po-deep`,children:r(t.runId,{limit:wt,compact:!0})}),t.state===`failed`&&t.error?P(`span`,{"data-testid":`run-error`,className:`truncate border-t border-po-border-soft px-3 py-1.5 text-sm text-po-red`,children:t.error}):null]}),F(`div`,{className:`flex shrink-0 items-center gap-3 border-t border-po-border-soft px-3 py-1.5`,children:[F(`span`,{className:`truncate text-sm text-po-dim`,children:[t.toolCount===void 0?`—`:`${t.toolCount} tools`,t.tokens===void 0?``:` · ${t.tokens.toLocaleString()} tk`,t.model?` · ${t.model.split(`/`).pop()??t.model}`:``]}),P(`span`,{className:`min-w-0 flex-1`}),P(Et,{sessionId:e,run:t,stopping:n,onOpenThread:i,onOpenDetail:a})]})]})})}function J({label:e,value:t,tone:n=`text-po-dim`}){return F(`div`,{className:`flex gap-2.5`,children:[P(`span`,{className:`w-11 shrink-0 text-sm text-po-dim`,children:e}),P(`span`,{className:`min-w-0 break-words text-base ${n}`,children:t})]})}function Ot({label:e,text:t,testId:n,tone:r}){return F(`div`,{className:`flex flex-col gap-1 rounded-md border border-po-border bg-po-deep px-3 py-2.5`,children:[P(`span`,{className:`text-base font-medium text-po-dim`,children:e}),P(`pre`,{"data-testid":n,className:`overflow-x-auto whitespace-pre-wrap break-words text-base leading-relaxed ${r??`text-po-text`}`,children:t})]})}function kt({sessionId:e,run:t,stopping:n,renderSlot:r,onClose:a}){let o=mt[t.state];return P(Se,{open:!0,onOpenChange:e=>{e||a()},children:F(c,{"data-testid":`run-sheet`,"aria-describedby":void 0,children:[F(b,{closeLabel:`close the run detail`,children:[P(i,{"data-testid":`sheet-agent`,children:Ke(t)}),P(f,{tone:o.tone,children:o.label}),P(`span`,{className:`min-w-0 flex-1`}),P(`span`,{className:`text-sm text-po-dim`,children:P(G,{run:t})}),r(Je.slot),P(gt,{sessionId:e,run:t,stopping:n})]}),F(re,{children:[F(`div`,{className:`flex flex-col gap-1.5`,children:[P(J,{label:`run`,value:t.runId}),t.taskRef?P(J,{label:`task`,value:t.taskRef,tone:`text-po-violet`}):null,P(J,{label:`model`,value:t.model??`the runtime default`}),P(J,{label:`cwd`,value:Ge(t.cwd)}),P(J,{label:`work`,value:`${t.toolCount===void 0?`no`:String(t.toolCount)} tools${t.tokens===void 0?``:` · ${t.tokens.toLocaleString()} tk`}`})]}),P(Ot,{label:`PROMPT FROM THE MAIN AGENT`,testId:`sheet-task`,text:t.task||`(no prompt recorded)`}),t.summary?P(Ot,{label:`REPORT`,testId:`sheet-summary`,text:t.summary}):null,t.error?P(Ot,{label:`FAILURE`,testId:`sheet-error`,text:t.error,tone:`text-po-red`}):null]})]})})}function At({sessionId:e,renderSlot:t,renderThread:n,openTransientTab:r,fileTabFor:i}){let a=N(W.store,t=>Qe(W.select(t,e))),{openRunId:o,stopRequested:s,autoOpenRunId:c}=N(W.store,t=>W.select(t,e)),l=N(z.store,t=>z.select(t,e));O(()=>{if(e!==null&&l.open)return Be(e)},[e,l.open]),O(()=>{if(c===void 0||e===null)return;let t=a.find(e=>e.runId===c);t&&r(xt(t)),it(e)},[c,a,e,r]);let u=o===void 0?void 0:a.find(e=>e.runId===o),d=e=>s.includes(e.runId),f=a.filter(e=>e.state===`running`||e.state===`queued`).length,p=a.filter(e=>e.state===`done`).length,m=a.filter(e=>e.state===`failed`||e.state===`stopped`).length;return F(`div`,{"data-testid":`subagents-panel`,className:`flex min-h-0 min-w-0 flex-1 overflow-hidden`,children:[F(`div`,{className:`@container flex min-w-0 flex-1 flex-col overflow-y-auto px-3 py-3 sm:px-[26px] sm:py-[18px]`,children:[F(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2 pb-3`,children:[P(`span`,{className:`text-lg font-semibold text-po-hi`,children:`Agents · this session`}),P(`span`,{className:`hidden min-w-0 flex-1 sm:block`}),P(`span`,{"data-testid":`subagents-tally`,className:`order-3 w-full text-sm text-po-dim sm:order-none sm:w-auto`,children:a.length===0?`no runs yet`:`${f} running · ${p} done · ${m} failed`}),P(S,{variant:`primary`,className:`ml-auto sm:ml-0`,"data-testid":`subagents-launch`,title:`pick an agent from the catalog and launch it`,onClick:()=>{e!==null&&(at(e,void 0),B(e))},children:`New agent run`})]}),a.length===0?F(`div`,{"data-testid":`subagents-empty`,className:`text-base text-po-dim`,children:[P(`p`,{children:`No runs yet`}),P(`p`,{children:`Start an agent run to get help with your work.`}),P(`p`,{className:`py-32 text-center text-sm`,children:`Agent runs will appear here once you start one.`})]}):F(T,{children:[P(`div`,{"data-testid":`subagents-grid`,className:`grid grid-cols-1 gap-4 @2xl:grid-cols-2`,children:e===null?null:a.map(t=>P(Dt,{sessionId:e,run:t,stopping:d(t),renderThread:n,onOpenThread:()=>{V(e),r(xt(t))},onOpenDetail:()=>{V(e),at(e,t.runId)}},t.runId))}),P(`span`,{className:`pt-3 text-sm text-po-dim`,children:`click a card to open the run's thread · the card menu holds details, stop and clear · finished runs leave the grid after 10m`})]})]}),e!==null&&l.open?P(pt,{sessionId:e,onClose:()=>V(e),onSource:t=>{let n=i(t.filePath);return n?()=>{V(e),r(n)}:void 0}}):null,u&&e!==null?P(kt,{sessionId:e,run:u,stopping:d(u),renderSlot:t,onClose:()=>at(e,void 0)}):null]})}function Y(){return{id:Ct,label:`Agents`,panel:At}}var jt=xe({label:`Launch Agent`,detail:`Choose an agent, review the task, then launch it.`,kinds:[`work-item`],order:10,run:e=>ze(e,Y)}),Mt=de({keys:`a r`,icon:t,statusKey:`po-team-agents`,activeSource:{subscribe(e){let t=W.store.subscribe(e);return()=>t.unsubscribe()},isActive(e){return $e(W.select(W.store.state,e)).some(e=>!U(e))}},transientTab:Y,order:10}),Nt=oe(Ve),Pt=oe(ot),Ft={queued:`waiting`,running:`running`,done:`done`,failed:`failed`,stopped:`done`};function It(e){return e.state===`failed`&&e.error?e.error:e.summary?e.summary.split(`
3
- `).find(e=>e.trim()!==``)??``:e.currentTool??e.tail.at(-1)??(e.state===`running`?``:e.state)}function Lt({sessionId:e,openTransientTab:t}){let n=N(W.store,t=>$e(W.select(t,e)));return n.length===0?F(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1`,children:[P(`p`,{"data-testid":`activity-summary-agents`,className:`text-sm text-po-dim`,children:`Idle`}),F(S,{variant:`link`,size:`sm`,"data-testid":`activity-agents-launch`,className:`h-auto gap-1 px-0 text-sm text-po-green`,onClick:()=>{e!==null&&(B(e),t(Y()))},children:[`Launch an agent`,P(he,{"aria-hidden":!0,className:`size-3.5`})]})]}):P(`div`,{"data-testid":`activity-agent-runs`,className:`flex flex-col gap-0.5`,children:n.map(n=>{let r=H(n),i=It(n);return P(S,{variant:`ghost`,size:`card`,"data-testid":`activity-run-${n.runId}`,"data-run-state":n.state,title:`open this run's conversation`,onClick:()=>{e!==null&&t(xt(n))},className:`min-w-0 gap-0.5 rounded-md px-1 py-1 hover:bg-po-panel`,children:F(`span`,{className:`flex min-w-0 items-center gap-2`,children:[P(C,{name:r.name,seed:r.seed,state:Ft[n.state],size:`sm`}),F(`span`,{className:`flex min-w-0 flex-1 flex-col text-left`,children:[F(`span`,{className:`flex min-w-0 items-baseline gap-1.5`,children:[P(`span`,{className:`truncate text-base font-semibold text-po-hi`,children:r.name}),r.role?P(`span`,{className:`truncate text-sm text-po-dim`,children:r.role}):null]}),i?P(`span`,{className:`truncate text-sm ${n.state===`failed`?`text-po-red`:`text-po-dim`}`,children:i}):null]}),F(`span`,{className:`shrink-0 text-sm text-po-dim`,children:[P(G,{run:n}),n.toolCount===void 0?``:` · ${n.toolCount} tools`]})]})},n.runId)})})}var Rt=we({component:Lt}),zt={key:`a`,label:`agents`,detail:`subagent resources and runs`},Bt=o({path:[zt,{key:`l`,label:`launch`,detail:`pick an agent and launch it`}],run:e=>{e.sessionId!==null&&B(e.sessionId),e.openTransientTab(Y())}}),Vt=o({path:[zt,{key:`r`,label:`runs`,detail:`runs in this session`}],run:e=>e.openTransientTab(Y())}),Ht=me({description:`Render an action beside the stop control in a subagent run detail sheet, using that run's props.`}),Ut=72,Wt=`…`;function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e){return typeof e==`string`?e:``}function Gt(e){switch(e.action){case`agents`:return Z(e.name);case`run`:{let t=Array.isArray(e.requests)?e.requests:[],n=t.map(e=>X(e)?Z(e.agent):``).filter(Boolean),r=`${t.length} agent${t.length===1?``:`s`}`;return n.length>0?`${r} · ${n.join(`, `)}`:r}case`status`:return e.id?`run`:`fleet`;default:return``}}function Kt(e){let t=e.split(`
4
- `);for(;t.length>0&&t.at(-1)?.trim()===``;)t.pop();return t.length===1&&t[0]===``?[]:t}function qt(e,t){let n=Kt(e);if(t.isPartial)return{lines:n.slice(-12),glyph:`running`,hidden:0};let r=t.expanded?n:n.slice(0,12),i=n.length-r.length;return t.isError?{lines:r,glyph:`failed`,hidden:i}:i>0?{lines:r,glyph:`more`,hidden:i}:r.length===0?{lines:r,glyph:`done`,hidden:0}:{lines:r,glyph:`none`,hidden:0}}function Q(e){let t=e.replace(/\s+/g,` `).trim();return t.length>Ut?`${t.slice(0,71)}${Wt}`:t}function Jt(e){return Array.isArray(e)?e.filter(X):[]}function Yt(e){return e.filter(e=>typeof e==`string`&&e.trim()!==``).join(` · `)}function Xt(e){if(e===`failed`||e===`error`)return`failed`;if(e===`running`||e===`starting`)return`running`;if(e===`queued`)return`waiting`;if(e===`complete`||e===`completed`||e===`stopped`)return`done`}function Zt(e){return e===`failed`||e===`error`?`error`:e===`complete`||e===`completed`?`ok`:e===`running`||e===`starting`?`running`:`idle`}function Qt(e,t){return e===0?`no ${t}s`:`${e} ${t}${e===1?``:`s`}`}function $t(e){let t=Jt(e).map((e,t)=>({key:`${Z(e.name)}-${t}`,label:Z(e.name),seed:Z(e.name),detail:Q(Z(e.description)),state:Z(e.source),tone:`idle`}));return{kind:`agents`,rows:t,summary:Qt(t.length,`agent`),tone:`idle`}}function en(e){let t=Jt(e).map((e,t)=>{let n=Z(e.runId);return{key:n||`${Z(e.agent)}-${t}`,label:Z(e.agent),seed:Z(e.agent),avatar:n?`running`:`failed`,detail:Q(Z(n?e.task:e.error))||(n?``:`unknown error`),state:n?`started`:`failed`,tone:n?`ok`:`error`}}),n=t.filter(e=>e.state===`started`).length,r=t.length-n;return{kind:`run`,rows:t,summary:r===0?`${n} started`:`${n} started · ${r} failed`,tone:r===0?`ok`:`error`}}function tn(e){let t=Jt(e).map((e,t)=>{let n=Z(e.status)||`starting`,r=H({agent:Z(e.agent),identity:Z(e.identity)||void 0});return{key:Z(e.runId)||`run-${t}`,label:r.name,seed:r.seed,avatar:Xt(n),detail:Q(Yt([r.role,e.currentTool,e.activityState,e.attentionReason,e.error])),state:n,tone:Zt(n)}});return{kind:`fleet`,rows:t,summary:Qt(t.length,`run`),tone:`idle`}}function nn(e){let t=Z(e.runId),n=X(e.status)?e.status:void 0,r=n?Z(n.state):``;if(!r)return{kind:`status`,rows:[],summary:`no status yet`,tone:`idle`};let i=H({agent:Z(n?.agent),identity:Z(n?.identity)||void 0});return{kind:`status`,rows:[{key:t,label:i.name,seed:i.seed,avatar:Xt(r),detail:Q(Yt([i.role,n?.activityState,n?.summary,n?.error])),state:r,tone:Zt(r)}],summary:``,tone:Zt(r)}}function rn(e,t){return{kind:`control`,rows:[],summary:e,tone:t}}function an(e){if(!X(e)||e.partial===!0)return null;if(Array.isArray(e.agents))return $t(e.agents);if(Array.isArray(e.outcomes))return en(e.outcomes);if(X(e.spawn)&&Array.isArray(e.spawn.outcomes))return en(e.spawn.outcomes);if(Array.isArray(e.runs))return tn(e.runs);if(Array.isArray(e.fleet))return tn(e.fleet);if(X(e.control))return rn(`stop requested`,`ok`);if(X(e.steer)){let t=Z(e.steer.state);return rn(`steer ${t}${e.steer.message?`: ${Q(Z(e.steer.message))}`:``}`,t===`failed`?`error`:`ok`)}return typeof e.runId==`string`?nn(e):null}function on(e,t){let n=Z(e.action),r=X(t)?Z(t.toName).trim():``;switch(n){case`send`:case`ask`:return{action:n,target:r||Z(e.to),message:Q(Z(e.message))};case`reply`:return{action:n,target:Z(e.requestId),message:Q(Z(e.message))};default:return{action:n,target:``,message:``}}}function sn(e){return X(e)?e.delivered===!0?{outcome:`delivered`,who:Z(e.to),reply:``}:e.state===`queued`?{outcome:`queued`,who:Z(e.to),reply:``}:typeof e.reply==`string`?{outcome:`answered`,who:Z(e.from),reply:e.reply}:typeof e.requestId==`string`&&typeof e.to==`string`?{outcome:`replied`,who:e.to,reply:``}:{outcome:`none`,who:``,reply:``}:{outcome:`none`,who:``,reply:``}}function cn(e){return X(e)?Z(e.sender):``}var ln={delivered:{tone:`neutral`,glyph:`✓`,text:`Delivered`},queued:{tone:`running`,glyph:void 0,text:`Queued, not yet confirmed`},replied:{tone:`neutral`,glyph:`✓`,text:`Replied`}},un={ask:`Asked`,send:`Message`,reply:`Reply`};function dn({name:e,chip:t,state:n,testId:r,children:i}){return F(`div`,{"data-testid":r,className:`flex items-start gap-2`,children:[P(C,{name:e,size:`sm`,...n?{state:n}:{}}),F(`div`,{className:`flex min-w-0 flex-col items-start gap-1`,children:[F(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-sm`,children:[P(`span`,{className:`truncate font-semibold text-po-hi`,children:e}),t]}),i]})]})}function fn({args:e,result:t,output:r,running:i,isError:a}){let o=on(e,t?.details),s=qt(r,{expanded:!1,isPartial:i,isError:a}),c=i||a?{outcome:`none`,who:``,reply:``}:sn(t?.details),l=c.outcome===`none`||c.outcome===`answered`?null:ln[c.outcome],u=typeof e.message==`string`?e.message.trim():``,d=o.action===`reply`?c.who:o.target,f=cn(t?.details),p=un[o.action];return P(n,{tone:ne({running:i,isError:a}),expandable:s.glyph===`more`,children:({expanded:e})=>{let t=e?qt(r,{expanded:!0,isPartial:i,isError:a}):s;return F(T,{children:[P(_,{title:`intercom`,children:F(`span`,{"data-testid":`tool-call-intercom`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[P(`span`,{className:`text-po-hi`,children:o.action}),d?F(`span`,{className:`shrink-0 text-po-cyan`,children:[`→ `,d]}):null]})}),F(pe,{"data-testid":`tool-result-intercom`,className:`flex flex-col gap-3`,children:[u&&!a?F(`div`,{"data-testid":`intercom-outgoing`,className:`flex flex-col items-end gap-1`,children:[F(`div`,{className:`flex min-w-0 items-center gap-2 text-sm`,children:[p?P(k,{tone:`neutral`,size:`xs`,children:p}):null,f?F(T,{children:[P(C,{name:f,size:`sm`}),P(`span`,{className:`truncate font-semibold text-po-hi`,children:f})]}):null]}),P(`p`,{className:`max-w-xl rounded-lg bg-po-tint-green px-3 py-2 text-base break-words whitespace-pre-wrap text-po-hi`,children:u}),l?P(y,{tone:l.tone,glyph:l.glyph,children:l.text}):null,i&&o.action!==`ask`?P(y,{tone:`running`,children:`Sending`}):null]}):null,i&&u&&o.action===`ask`?P(dn,{testId:`intercom-replying`,name:d||`reply`,state:`running`,chip:P(`span`,{className:`text-po-dim`,children:`is replying`}),children:F(`div`,{role:`status`,"aria-label":`${d||`The recipient`} is replying`,className:`flex items-center gap-1.5 rounded-lg bg-po-rail px-3 py-3`,children:[P(ie,{tone:`muted`,size:`md`,pulse:!0}),P(ie,{tone:`muted`,size:`md`,pulse:!0}),P(ie,{tone:`muted`,size:`md`,pulse:!0})]})}):null,c.outcome===`answered`?P(dn,{testId:`intercom-incoming`,name:c.who,chip:P(k,{tone:`green`,size:`xs`,children:`Replied`}),children:P(`p`,{className:`max-w-xl rounded-lg bg-po-rail px-3 py-2 text-base break-words whitespace-pre-wrap text-po-hi`,children:c.reply})}):null,a?P(`p`,{role:`alert`,className:`text-base break-words text-po-red`,children:t.lines.join(`
5
- `)||`Failed`}):null,!u&&!a&&t.lines.length>0?P(`p`,{className:`${e?`whitespace-pre-wrap break-words`:`truncate`} text-po-dim`,children:t.lines.join(`
6
- `)}):null,t.glyph===`more`?F(y,{expands:!0,children:[t.hidden,` more line(s)`]}):null]})]})}})}var pn=v({message:fn}),mn={running:{tone:`running`,text:`Running`},failed:{tone:`error`,text:`Failed`},done:{tone:`ok`,text:`Done`}},hn={ok:`ok`,error:`error`,running:`running`,idle:`neutral`},gn={ok:`ok`,error:`error`,running:`running`,idle:`ok`};function _n({row:e}){return F(`li`,{"data-testid":`tool-result-subagent-row`,className:`flex items-center gap-3 rounded-md px-2 py-1.5`,children:[P(C,{name:e.label,seed:e.seed,state:e.avatar}),F(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[P(`span`,{className:`truncate text-base font-semibold text-po-hi`,children:e.label}),e.detail?P(`span`,{className:`truncate text-sm text-po-dim`,children:e.detail}):null]}),e.state?P(f,{tone:hn[e.tone],size:`md`,className:hn[e.tone]===`neutral`?`bg-po-rail`:void 0,children:e.state}):null]})}function vn({args:e,result:t,output:r,running:i,isError:a,openTransientTab:o}){let s=typeof e.action==`string`?e.action:``,c=Gt(e),l=i||a?null:an(t?.details),u=l?Math.max(0,l.rows.length-8):0,d=l?null:qt(r,{expanded:!1,isPartial:i,isError:a});return P(n,{tone:ne({running:i,isError:a}),expandable:l?u>0:d?.glyph===`more`,children:({expanded:e})=>{let t=l||!d?null:e?qt(r,{expanded:!0,isPartial:i,isError:a}):d,n=!t||t.glyph===`none`||t.glyph===`more`?null:mn[t.glyph],f=l?e?l.rows:l.rows.slice(0,8):[];return F(T,{children:[P(_,{title:`subagent`,children:F(`span`,{"data-testid":`tool-call-subagent`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[P(`span`,{className:`text-po-dim`,children:s}),c?P(`span`,{className:`min-w-0 truncate text-po-dim`,children:c}):null]})}),F(pe,{"data-testid":`tool-result-subagent`,className:`flex flex-col gap-1`,children:[f.length>0?P(`ul`,{className:`-mx-2 flex flex-col`,children:f.map(e=>P(_n,{row:e},e.key))}):null,t&&t.lines.length>0?P(`pre`,{className:`${e?`whitespace-pre-wrap break-words`:`truncate`} text-po-dim`,children:t.lines.join(`
7
- `)}):null,!e&&u>0?F(y,{expands:!0,children:[u,` more`]}):null,n?P(y,{tone:n.tone,children:n.text}):null,t?.glyph===`more`?F(y,{expands:!0,children:[t.hidden,` more line(s)`]}):null,F(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1 ${f.length>0?`mt-1 border-t border-po-border-soft pt-2.5`:``}`,children:[l&&l.summary?P(y,{"data-testid":`tool-result-subagent-summary`,tone:gn[l.tone],children:l.summary}):null,F(S,{variant:`link`,size:`sm`,"data-testid":`tool-result-subagent-open`,onClick:()=>o(Y()),className:`h-auto gap-1 px-0 text-sm text-po-green`,children:[`Open subagents`,P(he,{"aria-hidden":!0,className:`size-3.5`})]})]})]})]})}})}var yn=v({message:vn}),$=(e,t)=>t===void 0?void 0:{...e,...t},bn=l({id:`subagents`,host:{get settingsSections(){return[$({id:`team`},Oe)]}},workspace:{get settingsSections(){return[$({id:`team`},ke)]}},session:{get activityGroups(){return[$({name:`agents`},Mt)]},get channels(){return[$({channel:`subagent_catalog`},Nt),$({channel:`subagent_runs`},Pt)]},get contextActions(){return[$({id:`launch-agent`},jt)]},get fills(){return[$({slot:`activity.agents`,id:`agents`},Rt)]},get leaderBindings(){return[$({id:`subagents.catalog`},Bt),$({id:`subagents.fleet`},Vt)]},get slots(){return[$({slot:`subagents.run-actions`},Ht)]},get toolRenderers(){return[$({tools:[`intercom`]},pn),$({tools:[`subagent`]},yn)]}}});export{bn as webPlugin};
@@ -1 +0,0 @@
1
- import{$n as e,Bn as t,Ct as n,Fn as r,Fr as i,Ft as a,Gn as o,I as s,In as c,It as l,Jt as u,Kn as d,Ln as f,Or as p,Pn as m,Qt as h,R as g,Rn as _,S as v,Sr as y,St as b,T as x,U as S,Wn as C,Zn as w,Zt as ee,_t as T,a as E,bt as D,d as O,fr as k,ft as A,g as j,gn as te,gt as M,ht as N,jt as ne,l as P,mt as re,n as ie,nr as ae,o as F,pt as oe,s as I,tt as se,ut as ce,vt as le,x as ue,xr as de,yt as L,zn as R}from"../chunks/po-web-runtime-DtS_FP_f.js";var z=`/api/plugins/vault/entries`,B=`secrets`,fe=/^[A-Z][A-Z0-9_]{0,63}$/u,V=`The request did not reach Po on your computer.`,H={namespace:``,key:``,value:``},U={"content-type":`application/json`};async function pe(e){let t=await e.json().catch(()=>void 0);return{error:typeof t?.error==`string`?t.error:`Po answered ${e.status}.`,...t?.field?{field:t.field}:{}}}function me({request:e,requestWithStepUp:t}){let[n,r]=j(),[i,a]=j(),[o,s]=j(``),[c,l]=j(),[u,d]=j(H),[f,p]=j(!1),[m,h]=j(),[g,_]=j(!1),v=P(async()=>{try{let t=await e(z);if(!t.ok)throw Error((await pe(t)).error);r(await t.json()),a(void 0)}catch(e){a(e instanceof Error?e.message:V)}},[e]);O(()=>{v()},[v]);let y=(e,t=H)=>{d(t),h(void 0),l(e)},b=n?.protection===`account`,x=e=>e.kind===`remove`?t(`${z}?${new URLSearchParams({namespace:e.entry.namespace,key:e.entry.key,revision:String(e.entry.revision),shared:String(e.entry.shared)}).toString()}`,{method:`DELETE`}):e.kind===`move`?t(`${z}/move`,{method:`POST`,headers:U,body:JSON.stringify({namespace:e.entry.namespace,key:e.entry.key,revision:e.entry.revision,shared:!e.entry.shared})}):t(z,{method:`PUT`,headers:U,body:JSON.stringify({namespace:u.namespace.trim(),key:u.key,text:u.value,expectRevision:e.kind===`replace`?e.entry.revision:null,shared:e.kind===`replace`?e.entry.shared:b||f})}),S=async()=>{if(c&&!g){_(!0);try{let e=await x(c);if(!e.ok){let t=await pe(e);h({field:t.field??`form`,message:t.error});return}l(void 0),d(H),await v()}catch{h({field:`form`,message:V})}finally{_(!1)}}};return{...n?{protection:n.protection,account:n.account,entries:n.entries}:{},...i?{error:i}:{},query:o,...c?{dialog:c}:{},draft:u,shareNew:f,...m?{draftError:m}:{},busy:g,onQueryChange:s,onAdd:()=>{p(!1),y({kind:`add`})},onReplace:e=>y({kind:`replace`,entry:e},{namespace:e.namespace,key:e.key,value:``}),onRemove:e=>y({kind:`remove`,entry:e}),onMove:e=>y({kind:`move`,entry:e}),onDraftChange:(e,t)=>{d(n=>({...n,[e]:t})),h(void 0)},onShareNewChange:p,onSubmit:()=>void S(),onCancel:()=>{g||l(void 0)},onRetry:()=>void v()}}var he=new Intl.DateTimeFormat(`en-GB`,{dateStyle:`medium`,timeZone:`UTC`});function W(e){return`${e.namespace}/${e.key}`}function ge(e,t){let n=t.trim().toLowerCase();return!n||W(e).toLowerCase().includes(n)}function _e(e){return`Updated ${he.format(new Date(e.updatedAt))} · revision ${e.revision}`}function ve(e){return e.length===1?`1 saved`:`${e.length} saved`}var ye={keyring:{badge:`Protected`,title:`Key kept in your system keychain`,detail:`Every secret is encrypted in Po’s database. The key that opens them stays in the keychain, never in a file.`},file:{badge:`File key`,title:`Key kept in a file next to your secrets`,detail:`This computer has no system keychain, so the key lives in vault/key.bin in your Po folder. Anyone who can read that folder can read your secrets.`},loading:{badge:`Checking`,title:`Opening the vault`,detail:`Po is loading the key that protects your secrets.`},closed:{badge:`Not opened yet`,title:`Opens the first time Po needs a secret`,detail:`The key that protects your secrets loads when a sign-in or a plugin first asks for one, or when you add a secret here.`},account:{badge:`In your account`,title:`Secrets kept in your Po account`,detail:`Every secret is encrypted in your account and opens only inside Po. Every Po signed in to this account can use them.`},unavailable:{badge:`Unavailable`,title:`Po could not open the vault`,detail:`Saved secrets are untouched. Sign-ins that need them wait until the vault opens again.`}},G={values:`Values are never shown here. Replace a secret to change it.`,add:`Saved encrypted on this computer. You will not be able to read it back here.`,addShared:`Saved encrypted in your Po account. You will not be able to read it back here.`,value:`Text, or JSON for structured values. Up to 64 KiB.`,namespace:`Usually the plugin that uses it, such as agiflow or mcp.github.`,remove:`The plugin that uses it will ask you to sign in again the next time it needs it.`,removeShared:`Every Po signed in to your account loses it. The plugin that uses it will ask you to sign in again.`,share:`Share with your account`,shareHint:`Every Po signed in to your account can use it, including Po Cloud.`},K={device:{title:`On this computer`,empty:`Nothing kept only on this computer.`},shared:{title:`Shared with your account`,empty:`Nothing shared yet. Share a secret from its menu.`}};function q(e){return e.shared?{menu:`Keep on this computer only`,title:`Keep on this computer only?`,detail:`Only this computer can use it. Other Po signed in to your account lose it.`,confirm:`Keep on this computer`,busy:`Moving…`}:{menu:`Share with your account`,title:`Share with your account?`,detail:`Every Po signed in to your account can use it, including Po Cloud. It leaves this computer’s vault.`,confirm:`Share secret`,busy:`Sharing…`}}var be={keyring:`size-4 text-po-green`,file:`size-4 text-po-yellow`,loading:`size-4 text-po-dim`,closed:`size-4 text-po-dim`,account:`size-4 text-po-green`,unavailable:`size-4 text-po-red`},xe={keyring:`ok`,file:`running`,loading:`neutral`,closed:`neutral`,account:`ok`,unavailable:`error`};function Se(e){let{children:t,protection:r,entries:i,error:a,query:o,busy:s}=e,c=a?`unavailable`:r??`loading`,u=ye[c],d=i!==void 0&&!a,f=i?.filter(e=>ge(e,o))??[],p=e.account===!0&&r!==`account`;return I(re,{"aria-busy":i===void 0||s,children:[t?F(A,{children:t}):null,I(L,{children:[F(b,{children:F(n,{children:`Protection`})}),F(ce,{children:I(N,{children:[F(`span`,{className:`flex size-9 shrink-0 items-center justify-center rounded-md bg-po-deep`,children:F(ne,{"aria-hidden":!0,className:be[c]})}),I(T,{children:[F(le,{children:u.title}),F(M,{children:u.detail})]}),F(l,{tone:xe[c],children:u.badge})]})})]}),I(L,{children:[I(b,{children:[F(n,{children:`Saved secrets`}),I(`div`,{className:`flex items-center gap-3`,children:[d&&i.length?F(`span`,{className:`text-sm text-po-dim`,children:ve(i)}):null,I(h,{variant:`primary`,disabled:!d||s,onClick:e.onAdd,children:[F(S,{className:`size-3.5`}),`Add secret`]})]}),F(D,{children:G.values})]}),a?I(`div`,{className:`flex flex-wrap items-center gap-3`,children:[F(`p`,{role:`alert`,className:`text-sm text-po-red`,children:a}),F(h,{variant:`ghost`,onClick:e.onRetry,children:`Try again`})]}):i===void 0?F(`p`,{role:`status`,className:`text-sm text-po-dim`,children:`Loading saved secrets…`}):i.length===0?F(ae,{title:`No secrets saved yet`,description:`Po saves one when you sign in to a provider or a plugin asks for a key.`,className:`py-12`}):I(E,{children:[I(`div`,{className:`relative`,children:[F(se,{"aria-hidden":!0,className:`pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-po-dim`}),F(k,{type:`search`,"aria-label":`Search saved secrets`,placeholder:`Search by name`,className:`w-full pl-9`,value:o,onChange:t=>e.onQueryChange(t.target.value)})]}),f.length===0?I(oe,{role:`status`,children:[`No saved secret matches “`,o.trim(),`”.`]}):p?[`device`,`shared`].map(t=>{let n=f.filter(e=>e.shared===(t===`shared`));return I(`div`,{className:`flex flex-col gap-2`,children:[F(`h3`,{className:`text-sm font-medium text-po-dim`,children:K[t].title}),n.length?F(Ce,{...e,label:K[t].title,entries:n,sharing:!0}):F(oe,{children:K[t].empty})]},t)}):F(Ce,{...e,label:`Saved secrets`,entries:f,sharing:!1})]})]}),F(we,{...e})]})}function Ce({entries:t,label:n,sharing:r,busy:i,openMenu:a,onReplace:s,onRemove:c,onMove:l}){return F(ce,{asChild:!0,children:F(`ul`,{"aria-label":n,children:t.map(t=>{let n=W(t);return F(N,{asChild:!0,children:I(`li`,{"data-testid":`vault-entry-${n}`,children:[F(`span`,{className:`flex size-9 shrink-0 items-center justify-center rounded-md bg-po-deep`,children:F(x,{"aria-hidden":!0,className:`size-4 text-po-dim`})}),I(T,{children:[I(le,{className:`truncate font-mono first-letter:normal-case`,children:[t.namespace,I(`span`,{className:`text-po-dim`,children:[` / `,t.key]})]}),F(M,{children:_e(t)})]}),I(C,{modal:!1,defaultOpen:a===n,children:[F(e,{asChild:!0,children:F(h,{variant:`ghost`,size:`icon-md`,"aria-label":`Actions for ${n}`,disabled:i,children:F(ue,{className:`size-4`})})}),I(o,{align:`end`,children:[F(d,{onSelect:()=>s(t),children:`Replace value`}),r?F(d,{onSelect:()=>l(t),children:q(t).menu}):null,F(w,{}),I(d,{variant:`destructive`,onSelect:()=>c(t),children:[F(ee,{className:`size-3.5`}),`Remove secret`]})]})]})]})},`${t.shared}:${n}`)})})})}function we({dialog:e,draft:n,draftError:i,busy:a,protection:o,account:s,shareNew:l,onDraftChange:d,onShareNewChange:p,onSubmit:g,onCancel:y}){let b=s===!0&&o!==`account`,x=o===`account`||b&&l,S=e=>i?.field===e?i.message:void 0,C=(e,t,r)=>{let i=S(e),o=i?`vault-${e}-error`:r?`vault-${e}-hint`:void 0,s=e===`value`?F(u,{id:`vault-${e}`,rows:4,className:`font-mono`,autoComplete:`off`,spellCheck:!1,value:n.value,disabled:a,"aria-invalid":i?!0:void 0,"aria-describedby":o,onChange:t=>d(e,t.target.value)}):F(k,{id:`vault-${e}`,className:`font-mono`,autoComplete:`off`,spellCheck:!1,value:n[e],disabled:a,"aria-invalid":i?!0:void 0,"aria-describedby":o,onChange:t=>d(e,t.target.value)});return I(`div`,{className:`flex flex-col gap-1.5`,children:[F(v,{htmlFor:`vault-${e}`,children:t}),s,i?F(`p`,{id:`vault-${e}-error`,role:`alert`,className:`text-sm text-po-red`,children:i}):r?F(`p`,{id:`vault-${e}-hint`,className:`text-sm text-po-dim`,children:r}):null]})},w=i?.field===`form`?F(`p`,{role:`alert`,className:`text-sm text-po-red`,children:i.message}):null;return F(m,{open:e!==void 0,onOpenChange:e=>e?void 0:y(),children:F(c,{children:e?.kind===`remove`?I(E,{children:[F(R,{children:I(t,{children:[`Remove `,F(`span`,{className:`font-mono`,children:W(e.entry)}),`?`]})}),I(r,{children:[F(f,{children:e.entry.shared?G.removeShared:G.remove}),w,I(_,{children:[F(h,{onClick:y,children:`Keep secret`}),F(h,{variant:`danger-outline`,disabled:a,onClick:g,children:a?`Removing…`:`Remove secret`})]})]})]}):e?.kind===`move`?I(E,{children:[F(R,{children:F(t,{children:q(e.entry).title})}),I(r,{children:[I(f,{children:[F(`span`,{className:`font-mono`,children:W(e.entry)}),`. `,q(e.entry).detail]}),w,I(_,{children:[F(h,{onClick:y,children:`Cancel`}),F(h,{variant:`primary`,disabled:a,onClick:g,children:a?q(e.entry).busy:q(e.entry).confirm})]})]})]}):e?I(`form`,{className:`contents`,onSubmit:e=>{e.preventDefault(),g()},children:[F(R,{children:F(t,{children:e.kind===`add`?`Add a secret`:I(E,{children:[`Replace `,F(`span`,{className:`font-mono`,children:W(e.entry)})]})})}),I(r,{className:`gap-4`,children:[F(f,{children:e.kind===`replace`?e.entry.shared?G.addShared:G.add:x?G.addShared:G.add}),e.kind===`add`?I(E,{children:[C(`namespace`,`Namespace`,G.namespace),C(`key`,`Name`)]}):null,C(`value`,e.kind===`add`?`Value`:`New value`,G.value),e.kind===`add`&&b?I(`div`,{className:`flex items-start gap-2`,children:[F(te,{id:`vault-share`,className:`mt-0.5`,checked:l,disabled:a,"aria-describedby":`vault-share-hint`,onCheckedChange:e=>p(e===!0)}),I(`div`,{className:`flex flex-col gap-0.5`,children:[F(v,{htmlFor:`vault-share`,children:G.share}),F(`p`,{id:`vault-share-hint`,className:`text-sm text-po-dim`,children:G.shareHint})]})]}):null,w,I(_,{children:[F(h,{type:`button`,onClick:y,children:`Cancel`}),F(h,{type:`submit`,variant:`primary`,disabled:a,children:a?`Saving…`:e.kind===`add`?`Save secret`:`Replace value`})]})]})]}):null})})}function Te(e){return F(Se,{...me(e)})}var Ee=p({label:`Vault`,detail:`See which sign-ins, tokens and API keys Po keeps for you, and add, replace or remove them.`,order:15,icon:x,component:Te}),J=y(void 0);function De(){J.update(()=>!0)}function Oe(e){let t=()=>{J.store.state&&(J.reset(),e())},n=J.store.subscribe(t);return t(),()=>n.unsubscribe()}function ke(){return I(g,{role:`menuitem`,density:`compact`,"data-testid":`composer-menu-secret`,className:`w-full text-po-text hover:bg-po-tint-blue`,onClick:De,children:[F(x,{className:`h-3 w-3 shrink-0`}),F(s,{density:`compact`,children:`Secret`})]})}var Ae=de({component:ke}),je=(e,t)=>ie.fetch(e,t),Y={name:``,value:``,sites:``,iosApps:``,macApps:``},Me=/[\s,]+/u,Ne=/^[a-z][a-z0-9+.-]*:\/\//iu,Pe=/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/u,X={name:`Use capital letters, digits and _, starting with a letter, such as GITHUB_LOGIN.`,value:`Enter the secret.`,where:`Add the site it signs in to, so Po types it nowhere else.`,app:`Use app bundle ids, such as com.example.app.`};function Z(e){return`{{ secrets.${e} }}`}function Fe(e){return e.toUpperCase().replace(/[^A-Z0-9_]+/gu,`_`)}function Ie(e){return e.entries.filter(e=>e.namespace===B).map(e=>({name:e.key,shared:e.shared}))}function Q(e){return[...new Set(e.split(Me).filter(Boolean))]}function Le(e){let t=Ne.test(e)?e:`https://${e}`;if(t.includes(`*`)||!URL.canParse(t))return;let n=new URL(t);if(!(n.protocol!==`https:`&&n.protocol!==`http:`||n.username||n.password))return n.origin}function Re(e,t){let n=(e,t)=>({ok:!1,field:e,message:t});if(!fe.test(e.name))return n(`name`,X.name);if(e.value===``)return n(`value`,X.value);let r=Q(e.sites),i=[];for(let e of r){let t=Le(e);if(t===void 0)return n(`sites`,`“${e}” is not a web address, such as github.com.`);i.push(t)}let a=Q(e.iosApps),o=Q(e.macApps);if(!a.every(e=>Pe.test(e)))return n(`iosApps`,X.app);if(!o.every(e=>Pe.test(e)))return n(`macApps`,X.app);let s=a.length>0||o.length>0;if(i.length===0&&!s)return n(`sites`,X.where);let c={value:e.value,purposes:[...i.length>0?[`browser`]:[],...s?[`input`]:[]],...i.length>0?{allowedOrigins:[...new Set(i)]}:{},...s?{allowedTargets:{...a.length>0?{ios:a}:{},...o.length>0?{computer:o}:{}}}:{}};return{ok:!0,request:{namespace:B,key:e.name,text:JSON.stringify(c),expectRevision:null,shared:t}}}var ze={name:{label:`Name`},value:{label:`Secret`,secret:!0},sites:{label:`Sites`,hint:`Where Po may type it, such as github.com. Separate several with commas.`},iosApps:{label:`iPhone apps (optional)`,hint:`App bundle ids, such as com.example.app.`},macApps:{label:`Mac apps (optional)`,hint:`App bundle ids, such as com.example.desktop.`}};function Be({open:e,onOpenChange:n,secrets:i,error:o,account:l,mode:u,draft:d,draftError:p,shareNew:y,busy:b,onPick:C,onAdd:w,onBack:ee,onDraftChange:T,onShareNewChange:D,onSubmit:O,onRetry:A}){let j=e=>{let{label:t,hint:n,secret:r}=ze[e],i=p?.field===e?p.message:void 0,a=e===`name`?`Prompts use it as ${Z(d.name||`NAME`)}.`:n,o=i?`secret-${e}-error`:a?`secret-${e}-hint`:void 0;return I(`div`,{className:`flex flex-col gap-1.5`,children:[F(v,{htmlFor:`secret-${e}`,children:t}),F(k,{id:`secret-${e}`,type:r?`password`:`text`,className:r?void 0:`font-mono`,autoComplete:r?`new-password`:`off`,spellCheck:!1,value:d[e],disabled:b,"aria-invalid":i?!0:void 0,"aria-describedby":o,onChange:t=>T(e,t.target.value)}),i?F(`p`,{id:`secret-${e}-error`,role:`alert`,className:`text-sm text-po-red`,children:i}):a?F(`p`,{id:`secret-${e}-hint`,className:`text-sm text-po-dim`,children:a}):null]})},M=o?I(`div`,{className:`flex items-center justify-between gap-3`,children:[F(`p`,{role:`alert`,className:`text-sm text-po-red`,children:o}),F(h,{onClick:A,children:`Try again`})]}):i===void 0?F(a,{label:`Loading secrets`}):i.length===0?F(ae,{title:`No saved secrets`,description:`Save a password or key once, then attach it to any prompt.`}):F(`div`,{role:`list`,className:`flex max-h-72 flex-col overflow-y-auto`,children:i.map(e=>F(`div`,{role:`listitem`,children:I(g,{density:`compact`,"data-testid":`secret-pick-${e.name}`,className:`w-full text-po-text hover:bg-po-tint-blue`,onClick:()=>C(e.name),children:[F(x,{className:`h-3 w-3 shrink-0 text-po-dim`}),F(s,{density:`compact`,className:`font-mono`,children:e.name}),e.shared?F(`span`,{className:`ml-auto text-xs text-po-dim`,children:`Shared`}):null]})},e.name))});return F(m,{open:e,onOpenChange:e=>b?void 0:n(e),children:F(c,{"data-testid":`secret-dialog`,children:u===`pick`?I(E,{children:[F(R,{children:F(t,{children:`Attach a secret`})}),I(r,{className:`gap-4`,children:[F(f,{children:`The agent gets its name, never the value. Po types it only on the sites and apps saved with it.`}),M,I(_,{children:[F(h,{onClick:()=>n(!1),children:`Cancel`}),I(h,{variant:i?.length===0?`primary`:void 0,onClick:w,children:[F(S,{className:`h-3 w-3`}),`New secret`]})]})]})]}):I(`form`,{className:`contents`,onSubmit:e=>{e.preventDefault(),O()},children:[F(R,{children:F(t,{children:`Save a secret`})}),I(r,{className:`gap-4`,children:[F(f,{children:y&&l?`Saved encrypted in your Po account. Po types it only where you list below.`:`Saved encrypted on this computer. Po types it only where you list below.`}),j(`name`),j(`value`),j(`sites`),j(`iosApps`),j(`macApps`),l?I(`div`,{className:`flex items-start gap-2`,children:[F(te,{id:`secret-share`,className:`mt-0.5`,checked:y,disabled:b,"aria-describedby":`secret-share-hint`,onCheckedChange:e=>D(e===!0)}),I(`div`,{className:`flex flex-col gap-0.5`,children:[F(v,{htmlFor:`secret-share`,children:`Share with your account`}),F(`p`,{id:`secret-share-hint`,className:`text-sm text-po-dim`,children:`Every Po signed in to your account can use it, including Po Cloud.`})]})]}):null,p?.field===`form`?F(`p`,{role:`alert`,className:`text-sm text-po-red`,children:p.message}):null,I(_,{children:[F(h,{type:`button`,disabled:b,onClick:ee,children:`Back`}),F(h,{type:`submit`,variant:`primary`,disabled:b,children:b?`Saving…`:`Save and attach`})]})]})]})})})}var Ve=`The request did not reach Po on your computer.`;async function He(e){let t=await e.json().catch(()=>void 0);return{...t,error:typeof t?.error==`string`?t.error:`Po answered ${e.status}.`}}function Ue(e,t,n=!0){let[r,i]=j(),[a,o]=j(!1),[s,c]=j(),[l,u]=j(`pick`),[d,f]=j(Y),[p,m]=j(),[h,g]=j(!1),[_,v]=j(!1),y=P(async()=>{try{let t=await e(z);if(!t.ok)throw Error((await He(t)).error);let n=await t.json();i(Ie(n)),o(n.account),c(void 0)}catch(e){c(e instanceof Error?e.message:Ve)}},[e]);O(()=>{n&&(u(`pick`),m(void 0),y())},[n,y]);let b=async()=>{if(_)return;let n=Re(d,a&&h);if(!n.ok)m({field:n.field,message:n.message});else{v(!0);try{let r=await e(z,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n.request)});if(!r.ok){let e=await He(r),t=e.field===`key`?`name`:e.field===`value`?`value`:`form`;m({field:t,message:e.error});return}t(Z(d.name)),f(Y),u(`pick`),y()}catch{m({field:`form`,message:Ve})}finally{v(!1)}}};return{...r?{secrets:r}:{},...s?{error:s}:{},account:a,mode:l,draft:d,...p?{draftError:p}:{},shareNew:h,busy:_,onPick:e=>t(Z(e)),onAdd:()=>{f(Y),m(void 0),g(!1),u(`add`)},onBack:()=>{_||u(`pick`)},onDraftChange:(e,t)=>{f(n=>({...n,[e]:e===`name`?Fe(t):t})),m(void 0)},onShareNewChange:g,onSubmit:()=>void b(),onRetry:()=>void y()}}function We({appendComposerDraft:e}){let[t,n]=j(!1);O(()=>Oe(()=>n(!0)),[]);let r=Ue(je,P(t=>{e(t),n(!1)},[e]),t);return F(Be,{open:t,onOpenChange:n,...r})}var Ge=de({component:We}),$=(e,t)=>t===void 0?void 0:{...e,...t},Ke=i({id:`vault`,host:{get settingsPanels(){return[$({id:`vault`},Ee)]}},session:{get fills(){return[$({slot:`composer-menu`,id:`secret`},Ae),$({slot:`overlay`,id:`secret-dialog`},Ge)]}}});export{Ke as webPlugin};
@@ -1 +0,0 @@
1
- import{A as e,Bn as t,Cr as n,Dr as r,F as i,Fn as a,Fr as o,G as s,In as c,K as l,L as u,Ln as d,Lt as f,M as p,Mr as m,N as h,P as g,Pn as _,Pr as v,Qt as y,Rn as b,Rr as x,Sn as S,Sr as C,Tn as w,Un as T,W as E,X as ee,Z as te,_r as ne,a as re,d as ie,dt as D,g as O,h as ae,hr as k,i as A,j as oe,kr as j,ln as se,mn as ce,mr as le,n as ue,o as M,q as de,qn as fe,r as pe,s as N,tn as me,w as he,wr as ge,xr as _e,zn as ve}from"../chunks/po-web-runtime-DtS_FP_f.js";var ye=`x-po-client-metadata`,be=`poClient`,xe=64;function Se(e){return typeof e==`string`&&/^[A-Za-z0-9_-]{1,64}$/u.test(e)}function Ce(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<=xe?t:void 0}function we(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Te(e){if(!we(e))return{status:`invalid`};if(Number.isSafeInteger(e.version)&&e.version!==1)return{status:`unsupported`};let t=Ce(e.deviceName);if(e.version!==1||!Se(e.deviceId)||e.instanceId!==void 0&&!Se(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&&(Ce(e[t])===void 0||Ce(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 Ee(e){let t=new TextEncoder().encode(JSON.stringify(e));return btoa(String.fromCharCode(...t)).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)}function De(e){let t=Te(e);if(t.status!==`ok`)throw Error(`Invalid Po client metadata`);let n=Ee(t.metadata);if(n.length>2048)throw Error(`Po client metadata exceeds encoded limit`);return n}function Oe(e){try{if(`preface`in e)return!we(e.preface)||!Object.hasOwn(e.preface,`poClient`)?{status:`absent`}:Object.keys(e.preface).length!==1||Ee(e.preface.poClient).length>2048?{status:`invalid`}:Te(e.preface.poClient);let t;if(`query`in e){let n=e.query.getAll(be);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?Te(JSON.parse(i)):{status:`invalid`}}catch{return{status:`invalid`}}}var P=16e3,ke=`application/vnd.po.pcm-s16le`,Ae=`x-po-voice-activity-state`,je=`x-po-voice-activity-level`,Me=`x-po-voice-activity-elapsed`,Ne=`x-po-voice-activity-epoch`,Pe=`x-po-voice-activity-speech-ms`,Fe=`x-po-voice-activity-echo-speech-ms`,Ie=`voice_media_wake`,F={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`},I={audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1};function Le(e){return{...I,audio:{...I.audio,deviceId:{exact:e}}}}function Re(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&&!Se(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 ze(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 Be(e,t){let n=Oe({header:t});return n.status===`ok`&&n.metadata.deviceId===e}var Ve=`voice_ownership`,He=/^[A-Za-z0-9._:-]+$/u;function Ue(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function We(e,t){return Object.keys(e).every(e=>t.includes(e))}function Ge(e,t=128){return typeof e==`string`&&e.length>0&&e.length<=t&&He.test(e)}function Ke(e){return Ge(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 qe(e){let t=Ue(e);if(t!==void 0&&We(t,[`type`,`version`,`deviceId`,`activeSessionId`,`handoff`])&&t.type===`browser-media-session`&&Se(t.deviceId)&&t.version===5&&(t.activeSessionId===null||Ke(t.activeSessionId))){if(t.handoff!==void 0){let e=Ue(t.handoff);if(e===void 0||!We(e,[`id`,`phase`,`sourceSessionId`,`targetSessionId`])||!Ge(e.id)||![`preparing`,`rebinding`,`failed`].includes(e.phase)||!Ke(e.sourceSessionId)||e.targetSessionId!==void 0&&!Ke(e.targetSessionId)||e.phase===`rebinding`&&e.targetSessionId===void 0)return}return t}}var Je=4,Ye=Symbol.for(`@agimon-ai/po-voice:web-media-page-state.v4`);function Xe(){return{version:Je,wakes:r(void 0),activeSession:C(null),handoff:C(void 0),browserState:C(void 0),realtimeControls:C(void 0),switchPending:C(void 0),runtime:C(void 0)}}function Ze(){let e=globalThis,t=e[Ye];if(t?.version===Je)return t;let n=Xe();return e[Ye]=n,n}var L=Ze(),Qe=L.wakes,R=L.activeSession,$e=L.handoff,z=L.browserState,et=L.runtime,tt=L.switchPending,B=L.realtimeControls,nt={subscribe(e){let t=[z,R,tt].map(t=>t.store.subscribe(e));return()=>{for(let e of t)e.unsubscribe()}},isActive(e){let t=z.store.state,n=t?.sessionId===null&&t.realtime!==void 0&&t.realtime.connection!==`closed`,r=e!==null&&tt.store.state?.sessionId===e;return n||R.store.state!==null||r}},rt={subscribe(e){let t=z.store.subscribe(e);return()=>t.unsubscribe()},isActive(){let e=z.store.state;return e?.sessionId===null&&e.realtime!==void 0&&e.realtime.connection!==`closed`}},it={channel:Ie,parse:Re,apply(e,t){Be(t.deviceId,pe())&&Qe.update(e,e=>e?.eventEpoch===t.eventEpoch&&t.sequence<=e.sequence?e:t)},drop(e){Qe.drop(e)}},at={channel:Ve,parse(e){return qe(e)??null},apply(e,t){Be(t.deviceId,pe())&&($e.update(()=>t.handoff),R.update(e=>e===t.activeSessionId?e:t.activeSessionId))},drop(e){$e.store.state===void 0&&R.update(t=>t===e?null:t)}};function ot(e,t,n,r,i){return ze(Qe,e,t,n,r,i)}var st=`/manual/transcribe`,ct=`x-po-audio-duration-ms`,lt=3e5,ut={sdpBytes:65536,eventBytes:65536,instructionsCharacters:16384,textCharacters:8192,identifierCharacters:256,pendingRequests:1,retainedRequests:128},dt=new Set([`session.started`,`session.updated`,`input_transcript.added`,`output_transcript.added`,`turn.done`,`delegation.created`]),V={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`},ft={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:F.clientConnect,response:void 0},clientDisconnect:{method:`POST`,path:F.clientDisconnect},clientHeartbeat:{method:`POST`,path:F.clientHeartbeat,response:void 0},clientEvents:{method:`GET`,path:F.clientEvents,query:[`clientId`,`connectionId`,`after`,`wait`],response:void 0},clientAudio:{method:`POST`,path:F.clientAudio,query:[`clientId`,`connectionId`,`captureId`]},clientCaptureStopped:{method:`POST`,path:F.clientCaptureStopped},clientPlaybackAudio:{method:`GET`,path:F.clientPlaybackAudio,query:[`clientId`,`connectionId`,`playbackId`,`wait`]},clientPlaybackResult:{method:`POST`,path:F.clientPlaybackResult},realtimeNegotiate:{method:`POST`,path:V.clientNegotiate,response:void 0},realtimeEvent:{method:`POST`,path:V.clientEvent},realtimeState:{method:`POST`,path:V.clientState},manualTranscribe:{method:`POST`,path:st,response:void 0}},H=le(ft,{scopes:[`host`,`workspace`,`session`],basePath:`voice`,transport:(e,t)=>ue.fetch(e,t),sessionAddress:x}),U=le(ft,{scopes:[`host`,`workspace`,`session`],basePath:`voice-media`,transport:(e,t)=>ue.fetch(e,t),sessionAddress:x}),pt=/^[⠀-⣿]\s*/u,mt=`voice auto:`,ht=`voice live:`,gt=`voice:`,_t=/\b(\d+:[0-5]\d)\b/u,vt={mode:`off`,phase:`idle`,label:`not listening`,detail:`start autonomous capture from the minor modes, or dictate one message with the voice tool.`,tone:`idle`,active:!1,microphoneMuted:!1,elapsed:``},yt=[{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 bt(e){let t=(e??``).replace(pt,``).trim();if(t===``)return vt;if(t.startsWith(mt)){let e=t.slice(11).trim(),n=e.includes(`microphone muted`),r=yt.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:``}:{...vt,mode:`auto`,label:e||`listening`,detail:``,tone:`live`,active:!0,microphoneMuted:n}}if(t.startsWith(ht))return{mode:`live`,phase:`listening`,label:`talking`,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``};if(t.startsWith(gt)){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?_t.exec(e)?.[1]??``:``}}return{mode:`auto`,phase:`listening`,label:t,detail:``,tone:`live`,active:!0,microphoneMuted:!1,elapsed:``}}function xt({state:e,takeOver:t,retry:n,mute:r,end:i,pending:a,error:o}){let s=e.kind===`deviceLive`,c=e.kind===`standby`,l=e.ownerName??`another device`;return N(`section`,{"aria-label":`Voice`,className:`flex flex-col gap-3`,children:[M(`h3`,{className:`text-lg font-semibold text-po-hi`,children:`Voice`}),N(`div`,{className:`flex items-center gap-2`,children:[M(T,{tone:s?`cyan`:c?`muted`:`magenta`}),M(`span`,{className:`text-base font-semibold text-po-hi`,children:c?`Voice is on standby`:s?`Live on this device`:`Voice is active on ${l}`})]}),M(`p`,{className:`text-sm leading-relaxed text-po-dim`,children:c?`Another window on this device is using voice. This window is not listening.`:s?`${e.deviceName??`This device`} · Microphone live. Other devices can run their own Live conversations separately.`:e.kind===`stale`?`Voice moved since you last checked. Take over from ${l} whenever you are ready.`:`This device is not listening. You can move this session’s voice here whenever you are ready.`}),e.kind===`conflict`||e.kind===`stale`?M(`div`,{children:M(y,{variant:`secondary`,disabled:a||!t,onClick:t,children:`Take over`})}):s?N(`div`,{className:`flex gap-2`,children:[M(y,{variant:`subtle`,disabled:a||!r,onClick:r,children:`Mute`}),M(y,{variant:`subtle`,disabled:a||!i,onClick:i,children:`End Live on this device`})]}):null,s?M(`p`,{className:`text-sm text-po-dim`,children:`Each device’s Live conversation is billed separately.`}):null,o?M(`p`,{role:`alert`,className:`text-sm text-po-red`,children:o}):null,o&&n?M(`div`,{children:M(y,{variant:`subtle`,disabled:a,onClick:n,children:`Try again`})}):null]})}var St={idle:`muted`,live:`cyan`,attention:`yellow`},Ct={idle:`text-po-dim`,live:`text-po-cyan`,attention:`text-po-yellow`};function wt({tone:e}){return M(`span`,{"aria-hidden":!0,className:`flex h-3 items-end gap-[2px]`,children:[3,7,5,9,4].map((t,n)=>M(`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 W({label:e,onClick:t,pending:n,...r}){return t===void 0?null:M(y,{variant:`subtle`,size:`xs`,disabled:n,onClick:t,...r,children:e})}function Tt(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 Et(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:Tt(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 Dt({state:e,picker:t,actions:n,pending:r,error:i,ownership:a,ownershipActions:o}){if(a)return M(xt,{state:a,takeOver:o?.takeOver,retry:o?.retry,mute:n.mute,end:n.end,pending:r,error:i});let s=Et(e),c=e.kind===`daily`&&e.view.microphoneMuted,l=e.kind===`live`&&e.realtime?.muted===!0,u=c||l?`unmute`:`mute`,d=e.kind===`live-failed`,f=e.kind===`daily`&&e.signInHint;return N(`div`,{"data-testid":`voice-activity`,"data-voice-phase":s.phase,className:`flex flex-col gap-2 px-1`,children:[t===void 0?null:N(ee,{"aria-label":`Voice for this session`,value:t.value,disabled:t.disabled||r,onValueChange:e=>t.onPick(e),className:`grid grid-cols-2 gap-1.5`,children:[M(te,{value:`live`,"data-testid":`voice-pick-live`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Live`}),M(te,{value:`legacy`,"data-testid":`voice-pick-legacy`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Daily work`})]}),N(`span`,{className:`flex min-w-0 items-center gap-2`,children:[M(T,{tone:St[s.tone],pulse:s.pulse}),M(`span`,{"data-testid":`voice-label`,className:`flex-1 truncate text-base font-semibold ${Ct[s.tone]}`,children:s.label}),s.elapsed?M(`span`,{"data-testid":`voice-elapsed`,className:`shrink-0 text-sm tabular-nums text-po-yellow`,children:s.elapsed}):null,s.meter?M(wt,{tone:s.tone}):null]}),e.kind===`daily`||e.kind===`live`?N(`span`,{className:`flex flex-wrap gap-1.5`,children:[M(W,{label:u,onClick:n.mute,pending:r,"aria-pressed":c||l,...e.kind===`daily`?{"data-testid":`voice-autonomous-microphone-toggle`,"aria-label":`${u} autonomous voice microphone`,title:`${u} autonomous voice microphone`}:{}}),M(W,{label:`interrupt`,onClick:e.kind===`live`?n.interrupt:void 0,pending:r,title:`Interrupt local output. Output stays silent until this realtime session ends.`}),M(W,{label:`end`,onClick:n.end,pending:r,"data-testid":`voice-end`})]}):null,s.detail&&!f?M(`span`,{"data-testid":`voice-detail`,role:d?`alert`:void 0,className:`text-sm leading-relaxed text-po-dim`,children:d&&n.useDailyWork!==void 0?`${s.detail} You can keep talking with daily work.`:s.detail}):null,f?N(`span`,{className:`flex flex-col items-start gap-2`,children:[M(`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.`}),n.signIn===void 0?null:M(y,{variant:`secondary`,size:`xs`,"data-testid":`voice-sign-in`,onClick:n.signIn,children:`sign in`})]}):null,d?N(`span`,{className:`flex flex-wrap gap-1.5`,children:[M(W,{label:`use daily work`,onClick:n.useDailyWork,pending:r,"data-testid":`voice-use-daily`}),M(W,{label:`end`,onClick:n.end,pending:r,"data-testid":`voice-end`})]}):null,e.kind===`live-elsewhere`||e.kind===`daily-elsewhere`?M(`span`,{className:`flex`,children:M(W,{label:e.kind===`live-elsewhere`?`move Live here`:`move daily work here`,onClick:e.kind===`live-elsewhere`?n.routeLiveHere:n.moveDailyWorkHere,pending:r,"data-testid":e.kind===`live-elsewhere`?`voice-global-live-transfer`:`voice-daily-move`})}):null,i===null?null:M(`span`,{role:`alert`,className:`text-sm leading-relaxed text-po-yellow`,children:i})]})}function Ot(e){return e instanceof Error?e.message:String(e)}function kt({sessionId:e,statuses:t,openSettings:n,registeredMinorModes:r}){let i=bt(t[`po-voice`]),a=A(z.store),o=A(B.store),s=A(R.store),c=A(tt.store),[l,u]=O(!1),[d,f]=O(null),[p,m]=O(!1),[h,g]=O(),_=r?.includes(`voice-auto`)===!0;ie(()=>{if(e===null||!_)return;let t=!1;return H.session(e).status().then(n=>{!t&&n.ok&&g({sessionId:e,realtime:n.data.media.realtime})}).catch(()=>{t||g({sessionId:e,realtime:!1})}),()=>{t=!0}},[_,e]);let v=e===null||(h?.sessionId===e?h.realtime:a?.realtime!==void 0||i.mode===`live`||c?.sessionId===e&&c?.mode===`live`),y=e!==null&&a?.sessionId===e?a.realtime:void 0,b=a?.sessionId===null?a.realtime:void 0,x=y??b,S=x!==void 0&&x.connection!==`closed`,C=o?.sessionId===null||o?.sessionId===e?o:void 0,w=e!==null&&c?.sessionId===e?{kind:`switching`,mode:c.mode}:e!==null&&a?.sessionId===e&&a.phase===`conflict`&&i.mode!==`off`?{kind:`conflict`}:i.mode===`auto`?{kind:`daily`,view:i,signInHint:p}:x?.connection===`failed`&&i.mode!==`manual`?{kind:`live-failed`,error:x.error??`the live provider did not answer.`}:e!==null&&i.mode!==`live`&&y===void 0&&b?.connection===`connected`?{kind:`live-elsewhere`}:i.mode===`live`||S?{kind:`live`,...x===void 0?{}:{realtime:x},interrupted:a?.realtimeOutputInterrupted===!0}:s!==null&&s!==e&&i.mode===`off`?{kind:`daily-elsewhere`}:i.mode===`manual`?{kind:`manual`,view:i}:{kind:`idle`,view:i},T=async e=>{if(!l){u(!0),f(null);try{await e()}catch(e){f(Ot(e))}finally{u(!1)}}},E=async(t,n,r,i)=>{if(e===null)throw Error(`Voice controls need a session.`);if((t===`activate`||t===`switch`)&&n!==`live`){let a=et.store.state;if(!a)throw Error(`Voice media is not ready in this browser.`);try{r=await a.prepareSessionActivation(e,i)}catch(r){throw z.update(r=>{if(r?.sessionId!==e||!r.ownershipConflict)return r;let i=r.ownershipConflict.owner.generation;return{...r,actions:{takeOver:()=>{T(()=>E(t,n,void 0,i))},retry:()=>{T(()=>E(t,n))}}}}),r}}if(t===`switch`&&n===`live`&&!r){let e=et.store.state;if(!e)throw Error(`Voice media is not ready in this browser.`);r=await e.prepareLiveActivation(i)}let a=await H.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;z.update(()=>({sessionId:e,phase:`conflict`,ownershipConflict:r,ownership:{kind:o?`stale`:`conflict`,ownerName:r.owner.deviceName},actions:{takeOver:()=>{T(()=>E(t,n,void 0,r.owner.generation))},retry:()=>{T(()=>E(t,n))}}}))}else if(!a.ok)throw Error(a.error||`Voice control request failed.`)},ee=async(t,n)=>{if(e===null)return;m(!1);let r={sessionId:e,mode:t};tt.update(()=>r);try{await n()}finally{tt.update(e=>e===r?void 0:e)}},te=(e,t)=>T(()=>ee(e,t)),ne=()=>T(async()=>{let e=await H.host.liveStatus();if(e.ok&&e.data.signedIn===!1){m(!0);return}if(!e.ok)throw Error(e.error);if(e.data.state!==`disabled`)return;let t=et.store.state;if(!t)throw Error(`Voice media is not ready in this browser.`);let n=await t.prepareLiveActivation();await ee(`live`,()=>E(`switch`,`live`,n))}),re=()=>te(`legacy`,async()=>{v&&await D(`end`),await E(`activate`,`legacy`)}),D=async e=>{let t=await H.host.liveControl({body:{action:e}});if(!t.ok)throw Error(t.error||`Live control request failed.`)},ae=()=>C?C.end():void T(()=>D(`end`)),k={},oe,j=(t,n,r=!1)=>{e!==null&&v&&(oe={value:n,disabled:r,onPick:t})};switch(w.kind){case`switching`:j(()=>void 0,w.mode,!0);break;case`daily`:if(e===null)break;j(e=>void(e===`live`?ne():void 0),`legacy`),i.phase!==`starting`&&i.phase!==`draining`&&(k.mute=()=>void T(()=>E(i.microphoneMuted?`unmute`:`mute`))),k.end=()=>void T(()=>E(`deactivate`)),n&&(k.signIn=()=>n(`providers`));break;case`live`:{let e=w.realtime?.muted===!0;j(e=>void(e===`legacy`?re():void 0),`live`),k.mute=()=>C?C.mute(!e):void T(()=>D(e?`unmute`:`mute`)),k.interrupt=()=>C?C.interrupt():void T(()=>D(`interrupt`)),k.end=ae;break}case`live-failed`:j(e=>void(e===`legacy`?re():void 0),`live`),e!==null&&(k.useDailyWork=()=>void re()),k.end=ae;break;case`live-elsewhere`:j(()=>void 0,`live`,!0),e!==null&&(k.routeLiveHere=()=>void T(async()=>{let t=await H.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&&(k.moveDailyWorkHere=()=>void T(()=>E(`activate`,`legacy`)))}let se=a?.sessionId===e||a?.sessionId===null?a:void 0;return M(Dt,{state:w,picker:oe,actions:k,pending:l,error:d,ownership:se?.ownership,ownershipActions:se?.actions})}function At(e){let t=A(z.store);return e.sessionId!==null||t?.sessionId!==null||t.realtime?.connection===`closed`||t.realtime===void 0?null:M(kt,{...e})}var jt=_e({slot:`activity`,id:`voice-global-live`,component:At}),Mt=1e4,Nt=15e3,Pt=15e3;function Ft(e){return new TextEncoder().encode(e).byteLength}function It(e){if(typeof e!=`object`||!e)return;let t=e.type;return typeof t==`string`?t:void 0}function G(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}var Lt=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()=>I,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),Pt,`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,G(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`||Ft(t)>ut.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=It(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)),dt.has(r))try{this.options.onEvent(t)}catch(t){this.fail(e,`Realtime event consumer failed: ${G(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: ${G(t)}`))}catch(t){this.fail(e,`Remote audio playback failed: ${G(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: ${G(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;Ft(t(o))>ut.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: ${G(t)}`)}})}validateEvent(e){if(Ft(e)>ut.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(It(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(Ft(e)>ut.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()}),Mt,`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()}),Nt,`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}},Rt=600,zt=P*120/1e3,Bt=-120,Vt=32768,Ht=2,Ut=P*1*Ht;function Wt(e,t,n){return Math.min(n,Math.max(t,e))}function Gt(e){return Math.round(e*10)/10}function Kt(e){if(e.byteLength===0||e.byteLength%Ht!==0)throw Error(`PCM activity input must contain complete 16-bit samples.`);let t=0;for(let n=0;n<e.byteLength;n+=Ht){let r=e[n]|e[n+1]<<8,i=(r>=32768?r-65536:r)/Vt;t+=i*i}let n=Math.sqrt(t/(e.byteLength/Ht));return n===0?Bt:20*Math.log10(n)}var qt=class{endpointSilenceMs;elapsedBytes=0;activityEpoch=0;consecutiveSpeechSamples=0;consecutiveEchoSpeechSamples=0;classifiedSpeechSamples=0;echoDiscriminatedSpeechSamples=0;trailingSilenceSamples=0;speechStarted=!1;endpointReached=!1;previousEchoDiscriminated=!1;constructor(e=Rt){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=Kt(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<zt)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>=zt&&(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/P*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:Gt(Wt(r,Bt,0)),elapsedMs:Math.round(this.elapsedBytes/Ut*1e3),epoch:this.activityEpoch,classifiedSpeechMs:Math.round(this.classifiedSpeechSamples/P*1e3),...n?.echoReferenceActive===!0?{echoDiscriminatedSpeechMs:Math.round(this.echoDiscriminatedSpeechSamples/P*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}},Jt=2e3,Yt=16e3,Xt=200,Zt=128,Qt=2097152,$t=409;function en(e){return e instanceof Error&&`status`in e&&e.status===$t}function tn(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 nn(e,t){return{playbackId:e,outcome:`failed`,error:t instanceof Error?`${t.name}: ${t.message}`:String(t)}}function rn(e){return{...e}}function an(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 on(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 sn=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=Jt;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=rn(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=Jt,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(en(i)&&(this.activeConnectionId!==n||tn(i))&&this.onConnectionState(`conflict`,i),r.abort(),this.closeRealtime(en(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),en(i)&&tn(i)){this.ownershipError=i;return}await on(t,e),t=Math.min(t*2,Yt)}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=rn(this.device.capabilities);if(an(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>=Zt){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 qt(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>Qt){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));en(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(),en(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=rn(this.device.capabilities);if(r!==void 0&&!an(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,nn(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,nn(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,Xt-e.length)}${e}`}},cn=globalThis,ln=Symbol.for(`@agimon-ai/po-voice:microphone-preferences.v2`),un=globalThis,K=un[ln]??=C({inputs:[]}),dn=`po.voice.microphone.v1`;function fn(){try{let e=cn.localStorage.getItem(dn);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 pn(e){try{cn.localStorage.setItem(dn,JSON.stringify(e))}catch{}}async function mn(){let e=(await cn.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 K.update(t=>({...t,inputs:e})),e}function hn(){return K.store.state.choice===void 0?new Promise(e=>{K.update(t=>({...t,choice:(t,n)=>{K.update(e=>({...e,choice:void 0})),e({deviceId:t,remember:n})}}))}):Promise.resolve({deviceId:null,remember:!1})}function gn(){K.store.state.choice?.(null,!1)}async function _n(){let e;try{(await cn.navigator.mediaDevices.enumerateDevices().catch(()=>[])).some(e=>e.kind===`audioinput`&&e.label)||(e=await cn.navigator.mediaDevices.getUserMedia(I));let t=await mn();if(t.length<2)return I;let n=t.map(e=>e.deviceId).sort(),r=fn();if(r!==void 0&&r.inputs.join()===n.join())return r.deviceId===null?I:Le(r.deviceId);let{deviceId:i,remember:a}=await hn();return a&&pn({deviceId:i,inputs:n}),i===null?I:Le(i)}finally{e?.getTracks().forEach(e=>e.stop())}}var vn=new URL(new URL(`../assets/browserCaptureWorklet-Droj0fW0-Droj0fW0.js`,import.meta.url).href,``+import.meta.url).href,yn=2,bn=32768,xn=2e3,Sn=300,Cn=500,wn=800,Tn=20,En=4,Dn=16,On=-55,kn=-50,An=.65,jn=.75,Mn=.25,Nn=.35,Pn=.35,Fn=.5,In=4,Ln=.98,Rn=.01,zn=P*xn/1e3,Bn=P*Sn/1e3,Vn=P*Cn/1e3,Hn=wn/1e3,Un=P*Tn/1e3;function Wn(e,t,n){return Math.min(n,Math.max(t,e))}function Gn(e){if(e.byteLength===0||e.byteLength%yn!==0)throw Error(`Echo-discrimination input must contain complete PCM16 samples.`);let t=new Float32Array(e.byteLength/yn),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)/bn;return t}function Kn(e){let t=new Uint8Array(e.length*yn),n=new DataView(t.buffer);for(let t=0;t<e.length;t+=1){let r=Wn(e[t]??0,-1,1);n.setInt16(t*yn,Math.round(r<0?r*bn:r*32767),!0)}return t}function qn(e,t){let n=Math.min(e.length,Math.max(0,zn-t.length)),r=new Float32Array(n+t.length);return n>0&&r.set(e.subarray(e.length-n)),r.set(t,n),r}function Jn(e){return e<=0?-1/0:10*Math.log10(e)}function Yn(e){if(e.length===0)return 0;let t=0;for(let n of e)t+=n*n;return t/e.length}function Xn(e){if(e.length===0)return 0;let t=0;for(let n of e)Math.abs(n)>=Ln&&(t+=1);return t/e.length}function Zn(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 Qn(e,t,n,r,i){let a=[],o=[];for(let s=0;s+Un<=i;s+=Un){let i=0,c=0;for(let a=0;a<Un;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/Un))),o.push(Math.log10(Math.max(2**-52,c/Un)))}return a.length<3?0:Zn(Float32Array.from(a),Float32Array.from(o),0,0,a.length,1)}function $n(e){return new Uint8Array(e.byteLength)}var er=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=Gn(e);if(!Number.isFinite(t))return this.unavailable(e,n);let r=t-n.length/P;this.pruneReferences(r);let i=this.renderReference(r,n.length);if(this.microphoneHistory=qn(this.microphoneHistory,n),this.referenceHistory=qn(this.referenceHistory,i.samples),!i.tracked)return{speechPcm:new Uint8Array(e),referenceActive:!1,speechDiscriminated:!1,state:`unavailable`};let a=Math.min(Bn,this.microphoneHistory.length),o=this.microphoneHistory.length-a,s=this.referenceHistory.length-a,c=Math.min(Vn,s),l=Math.max(0,s-c),u=this.referenceHistory.subarray(l),d=this.microphoneHistory.subarray(o),f=Jn(Yn(d));if(Jn(Yn(u))<On)return f>=kn?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:{speechPcm:$n(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`};if(a<Bn||c<=0||Xn(d)>Rn)return{speechPcm:$n(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`};let p=0,m=0;for(let e=0;e<=c;e+=Dn){let t=Zn(this.microphoneHistory,this.referenceHistory,o,s-e,a,En);Math.abs(t)>Math.abs(m)&&(m=t,p=e)}let h=Math.max(0,p-Dn),g=Math.min(c,p+Dn);for(let e=h;e<=g;e+=1){let t=Zn(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(Qn(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=Wn(x<=2**-52?0:b/x,0,In),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 T=S<=2**-52?0:w/S,E=new Float32Array(n.length),ee=this.microphoneHistory.length-n.length,te=this.referenceHistory.length-n.length-p;for(let e=0;e<n.length;e+=1)E[e]=(this.microphoneHistory[ee+e]??0)-C*(this.referenceHistory[te+e]??0);let ne=Kn(E),re=Jn(Yn(E));return m>=An&&T<=Pn?{speechPcm:$n(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:m>=An&&v<jn&&T>=Fn&&re>=kn?{speechPcm:ne,referenceActive:!0,speechDiscriminated:!0,state:`mixed`}:y<Mn&&v<Nn&&f>=kn?{speechPcm:new Uint8Array(e),referenceActive:!0,speechDiscriminated:!0,state:`near-end`}:v>=jn?{speechPcm:$n(e),referenceActive:!0,speechDiscriminated:!1,state:`echo`}:{speechPcm:$n(e),referenceActive:!0,speechDiscriminated:!1,state:`uncertain`}}resetCapture(){this.microphoneHistory=new Float32Array,this.referenceHistory=new Float32Array}reset(){this.references=[],this.resetCapture()}unavailable(e,t=Gn(e)){return this.microphoneHistory=qn(this.microphoneHistory,t),this.referenceHistory=qn(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/P,o=Math.min(i.endedAt??a,a);e<o+Hn&&e+t/16e3>=i.startedAt&&(r=!0);let s=Math.round((e-i.startedAt)*P),c=Math.round((o-i.startedAt)*P);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/P;e.endedAt=Math.max(e.startedAt,Math.min(t,n));let r=Math.ceil((e.endedAt-e.startedAt)*P),i=Math.max(0,r-Vn-Bn);e.samples=new Float32Array(e.samples.subarray(i,r)),e.startedAt+=i/P}pruneReferences(e){this.references=this.references.filter(t=>t.endedAt===void 0||e<=t.endedAt+Hn)}},tr=5e3,nr=class extends Error{};function rr(e){return typeof e==`object`&&!!e&&Number.isSafeInteger(e.id)}var ir=class{worker;onTerminalFailure;responseTimeoutMs;nextRequestId=0;generation=0;operation=Promise.resolve();pending=new Map;closed=!1;failure;constructor(e,t=()=>void 0,n=tr){this.worker=e,this.onTerminalFailure=t,this.responseTimeoutMs=n,e.onmessage=e=>{if(!rr(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 nr)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 nr(`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()}},ar=new URL(new URL(`../assets/silero_vad_v6.2.1-SjbCxFXk-SjbCxFXk.onnx`,import.meta.url).href,``+import.meta.url).href,or=new URL(new URL(`../assets/sileroVadWorker-D894njUe-DjN_BMWf.mjs`,import.meta.url).href,``+import.meta.url).href,sr=4096,cr=100,lr=`po-voice-capture`,ur=180,dr=5e3,fr=1e4,pr=.1,mr=10,q=2,hr=32767,gr=P*q*cr/1e3,_r=1e-8,vr=.05,yr=P*300/1e3;function br(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.samples instanceof Float32Array&&typeof t.capturedAt==`number`}function xr(){return typeof window<`u`&&typeof window.speechSynthesis?.speak==`function`}function Sr(){return typeof AudioContext==`function`}function Cr(){if(typeof SpeechSynthesisUtterance==`function`)return SpeechSynthesisUtterance;if(typeof window>`u`)return;let e=window.SpeechSynthesisUtterance;return typeof e==`function`?e:void 0}var wr=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/P;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*hr)),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}},Tr=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.`)},dr)}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}:{}}))}},Er=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%q!==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/q),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,P);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}:{}}))}},Dr=class{rebindProtocolSupported;microphoneConstraints;capabilities={capture:typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0,playback:xr()||Sr(),captureActivity:!1,autonomousOrchestration:!1,playbackDucking:xr()||Sr(),realtime:typeof RTCPeerConnection==`function`&&typeof navigator<`u`&&navigator.mediaDevices?.getUserMedia!==void 0};captureGeneration=0;captureDeviceId;constructor(e=!1,t=async()=>I){this.rebindProtocolSupported=e,this.microphoneConstraints=t}armUserGesture(){this.listenForMediaUnlock()}stream;context;workletInstalled=!1;activeCapture;activePlayback;speechDetector;preparingSpeechDetector;speechPreparation;listeningForMediaUnlock=!1;speechWarmup;speechWarmupTimer;echoDiscriminator=new er;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=_r;let s=new wr(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/q,a=(u??this.context.currentTime)+(d+i)/P;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)>vr&&(this.echoDiscriminator.resetCapture(),p=l/q+yr,u=n-(d+l/q)/P),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>=gr;)m(gr)},g,_;if(typeof AudioWorkletNode<`u`&&this.context.audioWorklet!==void 0){this.workletInstalled||=(await this.context.audioWorklet.addModule(vn),!0);let e=new AudioWorkletNode(this.context,lr);e.port.onmessage=e=>{br(e.data)&&h(e.data.samples,e.data.capturedAt)},g=e,_=()=>{e.port.onmessage=null,e.port.close()}}else{let e=this.context.createScriptProcessor(sr,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 Er(this.context,t,e.playbackId,this.echoDiscriminator)}else{this.finishSpeechWarmup(!1);let t=window.speechSynthesis,r=Cr();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(pr,Math.min(mr,e.rate/ur))),e.voice&&(i.voice=t.getVoices().find(t=>t.name===e.voice||t.voiceURI===e.voice)??null),n=new Tr(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(!xr()||this.activePlayback!==void 0||this.speechWarmup!==void 0)return;let e=window.speechSynthesis,t=Cr();if(t===void 0||(e.resume(),e.speaking||e.pending))return;let n=new t(`a`);n.volume=.01,n.rate=mr,n.onend=()=>this.finishSpeechWarmup(!1),n.onerror=()=>this.finishSpeechWarmup(!1),this.speechWarmup=n,this.speechWarmupTimer=setTimeout(()=>this.finishSpeechWarmup(!0),fr),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 ir(new Worker(or,{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(ar),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 Or(){let e=Oe({header:pe()});if(e.status!==`ok`||!e.metadata.instanceId)throw Error(`Voice requires the shell client instance identity.`);return e.metadata.instanceId}var kr=`application/json`,Ar=6e4,jr=200,Mr=8e3,Nr=2e4;function Pr(e){return typeof e.eventEpoch==`string`&&e.eventEpoch.length>0&&e.eventEpoch.length<=jr&&Number.isSafeInteger(e.heartbeatMs)&&(e.heartbeatMs??0)>0&&(e.heartbeatMs??0)<=Ar?{eventEpoch:e.eventEpoch,heartbeatMs:e.heartbeatMs}:void 0}function J(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 Fr(e){if(!e.ok)throw J(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 Ir(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 Y(e){return{method:`POST`,headers:{"content-type":kr},body:JSON.stringify(e)}}function Lr(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 Rr(e){try{e?.body?.cancel().catch(()=>void 0)}catch{}}async function zr(e,t,n,r,i,a=(e,t)=>ue.fetch(e,t)){let o=new AbortController,s=i??o.signal,c,l=!1,u,d,f=new Promise((e,t)=>{d=t}),p=e=>{l||(l=!0,u=e,o.abort(e),Rr(c),d(e))},m=()=>p(i?.reason??new DOMException(`Voice media control request was aborted.`,`AbortError`)),h=setTimeout(()=>p(Error(`Voice media control request timed out.`)),n);i?.addEventListener(`abort`,m,{once:!0});let g;try{g=a(e,{...t,signal:s})}catch(e){throw clearTimeout(h),i?.removeEventListener(`abort`,m),e}let _=g.then(async e=>{if(c=e,l)throw Rr(e),u;return r(e)});try{return i?.aborted&&m(),await Promise.race([_,f])}finally{clearTimeout(h),i?.removeEventListener(`abort`,m)}}var Br=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 U.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,t,n={}){if(!this.remote())return ue.fetch(t,n);let r=new Headers(n.headers),i=Oe({header:pe()});i.status===`ok`&&r.set(ye,De(i.metadata));let a=new Request(new URL(e,`http://po.local`),{...n,headers:r}),o=new Uint8Array(await a.arrayBuffer()),s=new URL(a.url).searchParams.get(`connectionId`)??void 0;if(!s&&o.byteLength>0)try{let e=JSON.parse(new TextDecoder().decode(o));typeof e.connectionId==`string`&&(s=e.connectionId)}catch{s=void 0}if(!s)throw Error(`Paired Voice request has no connection binding.`);if(!this.binding||this.binding.connectionId!==s||this.binding.expiresAt<=Date.now()+Mr){let e=await H.host.relayBinding({body:{target:this.sessionId,connectionId:s}});if(!e.ok)throw J(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:s,expiresAt:t.expiresAt}}let c=``;for(let e of o)c+=String.fromCharCode(e);let l=await H.host.relay({query:{binding:this.binding.id},body:{targetSessionId:``,method:a.method===`GET`?`GET`:`POST`,path:e,headers:[...a.headers.entries()],body:btoa(c)}});if(!l.ok)throw J(l);let u=l.data;if(!Number.isSafeInteger(u.status)||!Array.isArray(u.headers)||typeof u.body!=`string`)throw Error(`Paired Voice relay response is invalid.`);let d=atob(u.body),f=Uint8Array.from(d,e=>e.charCodeAt(0));return new Response(f.byteLength===0?null:f,{status:u.status,headers:u.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,t,n){this.push=void 0;let r=ue.active()?`remote`:`local`,i=this.claimForActivation;this.claimForActivation=!1;let a=this.takeoverGeneration;this.takeoverGeneration=void 0;let o=Fr(await this.declareClient(e,t,n,r,i,a));return this.controlLocation=r,this.push=this.sessionId===null?void 0:Pr(o),o}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,Fr(await this.declareClient(e,t,n,r,i))}async disconnect(e,t){try{let n={clientId:e,connectionId:t},r=this.sessionId===null?await U.host.clientDisconnect({body:n}):this.remote()?await this.remoteResult(F.clientDisconnect,``,Y(n)):await this.media().clientDisconnect({body:n});if(!r.ok&&r.status!==409)throw J(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 ot(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?U.host.clientConnect({body:o}):this.remote()?this.remoteResult(F.clientConnect,``,Y(o)):this.media().clientConnect({body:o})}async fetchEvent(e,t,n,r,i){let a=Lr(F.clientEvents,{clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}}),o={clientId:e,connectionId:t,after:n,...i?{wait:`0`}:{}},s=this.sessionId===null?U.host.clientEvents.url({query:o}):this.remote()?``:this.media().clientEvents.url({query:o});return zr(s,{},Mr,async e=>{if(e.status!==204){if(!e.ok)throw await Ir(e);return await e.json()}},r,(e,t)=>this.fetch(a,s,t))}heartbeat(e,t){let n=F.clientHeartbeat,r=this.sessionId===null?U.host.clientHeartbeat.url():this.remote()?``:this.media().clientHeartbeat.url();return zr(r,Y({clientId:e,connectionId:t}),Mr,async e=>{if(!e.ok)throw await Ir(e);let t=Re(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":ke,...i===void 0?{}:{[Ae]:i.state,[je]:String(i.levelDbfs),[Me]:String(i.elapsedMs),...i.epoch===void 0?{}:{[Ne]:String(i.epoch)},...i.classifiedSpeechMs===void 0?{}:{[Pe]:String(i.classifiedSpeechMs)},...i.echoDiscriminatedSpeechMs===void 0?{}:{[Fe]:String(i.echoDiscriminatedSpeechMs)}}},s=new Blob([new Uint8Array(r)],{type:ke}),c=this.remote()?await this.remoteResult(Lr(F.clientAudio,a),``,{method:`POST`,headers:o,body:s}):await this.media().clientAudio({query:a,headers:o,body:s});if(!c.ok)throw J(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(F.clientCaptureStopped,``,Y(i)):await this.media().clientCaptureStopped({body:i});if(!a.ok)throw J(a)}async receivePlaybackAudio(e,t,n,r){let i=[],a=0,o=Lr(F.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 Ir(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(F.clientPlaybackResult,``,Y(r)):await this.media().clientPlaybackResult({body:r});if(!i.ok)throw J(i)}async realtimeNegotiate(e,t,n,r,i){let a=V.clientNegotiate,o=this.sessionId===null?U.host.realtimeNegotiate.url():this.remote()?``:this.media().realtimeNegotiate.url();return zr(o,Y({clientId:e,connectionId:t,activationId:n,sdp:r}),Nr,async e=>{if(!e.ok)throw await Ir(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?U.host.realtimeEvent.url():this.remote()?``:this.media().realtimeEvent.url();await this.postRealtime(V.clientEvent,i,{clientId:e,connectionId:t,activationId:n,event:r})}async realtimeState(e,t,n,r){let i=this.sessionId===null?U.host.realtimeState.url():this.remote()?``:this.media().realtimeState.url();await this.postRealtime(V.clientState,i,{clientId:e,connectionId:t,activationId:n,state:r})}postRealtime(e,t,n){return zr(t,Y(n),Mr,async e=>{if(!e.ok)throw await Ir(e)},void 0,(n,r)=>this.fetch(e,t,r))}},Vr=class{device=new Dr(!0,_n);clientId=Or();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(R.store.state),t=R.store.subscribe(e),n=$e.store.subscribe(e);this.unsubscribe=()=>{t.unsubscribe(),n.unsubscribe()},window.addEventListener(`pagehide`,this.closeOnPageHide,{once:!0}),this.select(R.store.state)}focus(e){}close(){if(this.closed)return;this.closed=!0,gn(),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||z.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 sn(this.clientId,`global-${crypto.randomUUID()}`,new Br(null,e,t),n,(e,n)=>{if(this.globalClient!==r)return;e===`conflict`&&this.reportOwnership(null,n,t);let i=z.store.state;i?.sessionId===null&&(e===`disconnected`&&i.realtime?.connection!==`failed`?z.reset():e!==`disconnected`&&z.update(()=>({...i,phase:e})))},(e,t)=>{if(this.globalClient!==r)return;if(e===void 0){if(z.store.state?.sessionId===null&&z.reset(),B.store.state?.sessionId===null&&B.reset(),t)return;this.globalClient=void 0,r.stop(!1);return}let n=z.store.state;z.update(()=>({sessionId:null,phase:n?.sessionId===null?n.phase:`connected`,realtime:e,realtimeOutputInterrupted:n?.sessionId===null?n.realtimeOutputInterrupted:void 0})),B.update(()=>({sessionId:null,mute:e=>this.controlGlobal(e?`mute`:`unmute`),interrupt:()=>{r.interruptRealtime(),this.controlGlobal(`interrupt`);let e=z.store.state;e?.sessionId===null&&z.update(()=>({...e,realtimeOutputInterrupted:!0}))},end:()=>{r.endRealtime(),this.controlGlobal(`end`)}}))},e=>new Lt(e,_n),e=>this.openSession?.(e)),this.globalClient=r,r.start()}catch(e){if(this.closed||z.store.state?.sessionId)return;let t=e instanceof Error?e.message:String(e);z.update(()=>({sessionId:null,phase:`conflict`,realtime:{connection:`failed`,listening:!1,speaking:!1,muted:!1,error:t}}))}}controlGlobal(e){H.host.liveControl({body:{action:e}}).then(e=>{if(!e.ok)throw Error(e.error)}).catch(e=>{let t=z.store.state;(t===void 0||t.sessionId===null)&&z.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=$e.store.state,n=R.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 sn(this.clientId,`connection-${crypto.randomUUID()}`,new Br(e,n,r),this.device,(t,n)=>{this.client===i&&this.boundSessionId===e&&(t===`disconnected`?z.store.state?.sessionId===e&&z.reset():(z.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`&&z.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=z.store.state;n?.sessionId===e&&z.update(()=>({...n,...t===void 0?{}:{realtime:t},...t===void 0?{realtime:void 0,realtimeOutputInterrupted:void 0}:{}}))},e=>new Lt(e,_n)),this.client=i,this.boundSessionId=e,B.store.state?.sessionId!==null&&B.update(()=>({sessionId:e,mute:e=>i.muteRealtime(e),interrupt:()=>{i.interruptRealtime();let t=z.store.state;t?.sessionId===e&&z.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=Oe({header:pe()}),a=i.status===`ok`&&i.metadata.deviceId===r.owner.deviceId;z.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&&z.store.state?.sessionId===t&&z.reset(),t!==void 0&&B.store.state?.sessionId===t&&B.reset(),await e?.stop(!1)}};function Hr(e){let t=et.store.state;return t===void 0&&(t=new Vr,et.update(()=>t)),e.mount?.scope===`session`&&t.focus(e.mount.sessionId),e.openSession&&(t.openSession=t=>e.openSession?.(t)),()=>void 0}var Ur=v(Hr),Wr={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`}]},Gr=j({...Wr,icon:i}),Kr=j({...Wr,icon:i}),qr=k({name:`voice`,keys:`v e`,statusKey:`po-voice`,activeSource:nt,hideWhenEmpty:!0,marksBackgroundWork:!1,placement:`bottom`,order:60}),Jr=ne(it),Yr=ne(at),Xr=_e({data:rt}),Zr=_e({slot:`activity.voice`,id:`voice`,component:kt}),Qr=1e3,$r=100,ei=1e4,ti=3e3,ni=.01,ri=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`],ii=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))>=ni)return this.lastSpeechAt=t,!1;let r=this.lastSpeechAt??this.startedAt,i=this.speechDetected?ti:ei;return t-r>=i}};function ai(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 ii;a=setInterval(()=>{o.getFloatTimeDomainData(s),c.observe(s,Date.now())&&t(c.speechDetected)},$r),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 oi(){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(I),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:ai}}async function si(e){e??=oi();let t=ri.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(lt,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,lt);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(Qr);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 ci(e){if(typeof e!=`object`||!e||!(`transcript`in e))return;let t=e.transcript;return typeof t==`string`?t:void 0}async function li(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 U.session(t).manualTranscribe({headers:{"content-type":e.type,[ct]:String(n)},body:e,...r===void 0?{}:{signal:r}}),a=ci(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 ui={start:si,transcribe:async(e,t,n,r)=>await li(e,t,n,r)},di=class{append;changed;dependencies;state={phase:`idle`};recording;transcription;generation=0;constructor(e,t,n=ui){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()}},fi=`manual voice is unavailable while autonomous voice is active`;function pi({error:e,onDismiss:t,children:n}){return N(E,{open:e!==void 0,onOpenChange:e=>{e||t()},children:[M(s,{asChild:!0,children:n}),N(de,{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:[M(fe,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),M(`span`,{className:`min-w-0 flex-1 break-words`,children:e}),M(l,{"aria-label":`dismiss`,className:`shrink-0 rounded-sm p-0.5 hover:bg-po-tint-red`,children:M(w,{"aria-hidden":!0,className:`size-3.5`})})]})]})}function mi({sessionId:e,appendComposerDraft:t,statuses:n,registeredMinorModes:r}){let a=A(R.store,e=>e),o=A(z.store),s=bt(n[`po-voice`]),[c,l]=O({phase:`idle`}),u=ae(void 0);u.current??=new di(t,()=>{l(u.current?.snapshot()??{phase:`idle`})});let d=c.phase,p=c.error,m=o?.sessionId===null&&o.realtime!==void 0&&o.realtime.connection!==`closed`,h=s.mode===`auto`||s.mode===`live`||a!==null||m;ie(()=>{let e=u.current;return()=>e?.dispose()},[]),ie(()=>{u.current?.setAppend(t)},[t]),ie(()=>{u.current?.reset()},[e,h]);let g=()=>{h||u.current?.toggle(e)},_=!h&&d===`recording`,v=h?fi:p??(_?`stop voice recording and fill the prompt`:d===`transcribing`?`transcribing voice recording`:d===`starting`?`starting voice recording`:`start voice recording`),b=h?`blocked`:d,x=p&&!h?`text-po-red`:`text-po-dim`;return r?.includes(`voice-auto`)?M(pi,{error:h?void 0:p,onDismiss:()=>u.current?.reset(),children:M(y,{variant:_?`danger-outline`:`ghost`,size:`icon-md`,"data-testid":`composer-voice-action`,"data-voice-mode":h?`auto`:_?`manual`:`off`,"data-voice-phase":b,"aria-label":v,title:v,disabled:e===null||h||d===`starting`||d===`transcribing`,onClick:g,className:`shrink-0 ${x}`,children:_?M(f,{className:`size-3 fill-current`}):d===`starting`||d===`transcribing`?M(he,{className:`size-4 animate-spin`}):M(p&&!h?fe:i,{className:`size-4`})})}):null}var hi=_e({slot:`composer-actions`,id:`voice`,component:mi});function gi(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 _i(){let{inputs:e,choice:n}=A(K.store,e=>e),[r,i]=O(0);if(n===void 0)return null;let o=gi(e),s=r<o.length?r:0,l=t=>{let r=e[o.indexOf(t)];r!==void 0&&n(r.deviceId,!0)};return M(_,{open:!0,onOpenChange:e=>{e||n(null,!1)},children:N(c,{width:`sm`,"data-testid":`voice-microphone-dialog`,"aria-describedby":void 0,onKeyDown:e=>se(e,{options:o,cursor:s,onCursorChange:i,onSelect:l}),children:[M(ve,{children:M(t,{children:`choose a microphone`})}),N(a,{children:[M(d,{children:`autonomous voice found more than one input. this browser remembers the one you pick.`}),M(u,{options:o,cursor:s,onCursorChange:i,onSelect:l,testIdPrefix:`voice-microphone-option`}),N(b,{className:`flex-col items-stretch`,children:[N(`span`,{className:`w-full text-sm text-po-dim`,children:[ce(o.length),` · esc uses the browser default once`]}),M(y,{variant:`outline`,size:`md`,"data-testid":`voice-microphone-default`,onClick:()=>n(null,!0),children:`always use browser default`})]})]})]})})}var vi=_e({slot:`overlay`,id:`voice`,component:_i}),yi=n({id:`voice.toggle`,path:[{key:`v`,label:`voice`,detail:`autonomous voice capture`},{key:`e`,label:`toggle`,detail:`start or stop autonomous capture`}],command:`minor voice-auto`}),bi=v(Hr),xi=ge({name:`voice`,modeId:`voice-auto`,keys:`v e`,icon:i,statusKey:`po-voice`,order:60}),Si=`describe_voice_tools`,Ci=`use_voice_tools`,wi=`narrate`,Ti=`transfer_voice`,Ei=6,Di=8,Oi=72,ki={tone:`error`,glyph:`✗`,label:`failed`},Ai={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:ki,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 X(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function ji(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=X(e);return t?.type===`text`&&typeof t.text==`string`?[t.text]:[]}):[]}function Fi(e){if(e)try{return X(JSON.parse(e))}catch{return}}function Ii(e){return X(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(X).filter(ji):[]}function Bi(e,t){if(e===`narrate`){let e=typeof t.text==`string`?Mi(t.text):``,n=e.length>Oi?`${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(X).filter(ji).map(Vi).filter(Boolean);if(t.length>0)return t.join(` | `)}return`value`}function Hi(e){let t=X(e),n=X(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=X(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(X).filter(ji):[],r=Array.isArray(e.conflicts)?e.conflicts.map(X).filter(ji):[],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,Ei),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=X(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(X(e.error),`message`)}function Ji(e,t){let n=Z(e,`name`)??`capability`,r=Z(e,`status`)??`failed`,i=Ai[r]??ki,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(X).filter(ji):[],r=Array.isArray(e.errors)?e.errors.map(X).filter(ji):[],i=Ai[Z(e,`status`)??`failed`]??ki,a=`${i.glyph} Voice batch ${i.label} · ${n.length} ${Li(n.length,`call`)}`,o=t?n:n.slice(0,Di),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=X(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=Ai[i]??ki;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=X(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||X(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(X(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:t,args:n,result:r,running:i,isError:a}){if(t===`narrate`){let e=na(n);return N(`div`,{role:`group`,"aria-label":`narration`,"data-testid":`narration-message`,"data-narration-state":i?`playing`:a?`failed`:`complete`,className:`flex min-w-0 items-start gap-2 text-base text-po-text`,children:[M(me,{"aria-hidden":`true`,className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-po-magenta`}),M(`p`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:e||`Narration unavailable.`})]})}let o=Bi(t,n),s=ia(t,r,{expanded:!1,isError:a,isPartial:i}),c=ia(t,r,{expanded:!0,isError:a,isPartial:i}),l=ta(t,r,{expanded:!1,isError:a,isPartial:i}),u=a?ra(r):``;return M(e,{tone:S({running:i,isError:a}),expandable:!a&&c.length>s.length,children:({expanded:e})=>N(re,{children:[M(p,{title:t,children:N(`span`,{"data-testid":`tool-call-${t}`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[N(`span`,{className:`shrink-0 font-semibold text-po-hi`,children:[o.glyph,` `,o.action]}),o.detail?M(`span`,{className:`min-w-0 truncate ${o.detailIsName?`text-po-blue`:`text-po-dim`}`,children:o.detail}):null]})}),a?u.length>0?M(oe,{"data-testid":`tool-result-${t}`,children:M(`p`,{className:`whitespace-pre-wrap break-words text-po-red`,children:u})}):null:M(oe,{"data-testid":`tool-result-${t}`,children:i&&r===null?M(h,{tone:`running`,children:`running`}):l.kind===`status`?M(sa,{status:l.status}):l.kind===`fields`?M(ca,{fields:l.fields}):M(g,{lines:e?c:s})})]})})}var oa={active:`green`,pending:`yellow`,idle:`neutral`};function sa({status:e}){return N(`div`,{className:`flex flex-col gap-2`,children:[N(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[M(D,{tone:oa[e.phase],children:`voice ${e.state}`}),M(D,{tone:`blue`,children:`mode ${e.mode}`}),M(D,{tone:e.muted?`yellow`:`neutral`,children:e.muted?`mic muted`:`mic on`}),e.manual===void 0?null:M(D,{children:`dictation ${e.manual}`})]}),e.error===void 0?null:M(`p`,{className:`break-words text-po-red`,children:e.error})]})}function ca({fields:e}){return e.length===0?M(`p`,{className:`text-po-faint`,children:`No result details.`}):M(`dl`,{className:`grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-4 gap-y-0.5`,children:e.map(e=>N(`div`,{className:`contents`,children:[M(`dt`,{className:`truncate text-po-dim`,children:e.key}),M(`dd`,{className:`break-words text-po-text`,children:e.value})]},e.key))})}var la=m({tools:[wi],timelinePresentation:`message`,message:aa}),ua=m({tools:[Si,Ci,Ti],message:aa}),$=(e,t)=>t===void 0?void 0:{...e,...t},da=o({id:`voice`,host:{get fills(){return[$({slot:`activity`,id:`voice`},jt)]},get settingsSections(){return[$({id:`voice`},Gr)]},get start(){return Ur}},workspace:{get settingsSections(){return[$({id:`voice`},Kr)]}},session:{get activityGroups(){return[$({name:`voice`},qr)]},get channels(){return[$({channel:`voice_media_wake`},Jr),$({channel:`voice_ownership`},Yr)]},get fills(){return[$({slot:`approval.voice-hint`,id:`approval-voice-hint`},Xr),$({slot:`activity.voice`,id:`voice`},Zr),$({slot:`composer-actions`,id:`voice`},hi),$({slot:`overlay`,id:`voice`},vi)]},get leaderBindings(){return[$({id:`voice.toggle`},yi)]},get minorModes(){return[$({name:`voice`},xi)]},get start(){return bi},get toolRenderers(){return[$({tools:[`narrate`]},la),$({tools:[`voice`]},ua)]}}});export{da as webPlugin};