@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.
- package/dist/assets/assets/{CodeEditorView-C_mYLn6M.js → CodeEditorView-BHaOMRjc.js} +2 -2
- package/dist/assets/assets/{abnfDiagram-WEYOIA3C-DefVXGFV.js → abnfDiagram-WEYOIA3C-CDWx0dCZ.js} +2 -2
- package/dist/assets/assets/{architecture-WOLXFQ4H-Ftqji05b.js → architecture-WOLXFQ4H-CVl8TlUa.js} +1 -1
- package/dist/assets/assets/{architectureDiagram-ZHVYKT53-D8aOrisO.js → architectureDiagram-ZHVYKT53-B-9U5J2m.js} +2 -2
- package/dist/assets/assets/{blockDiagram-RJAE7QA3-COb4aakG.js → blockDiagram-RJAE7QA3-DeAmR8GR.js} +2 -2
- package/dist/assets/assets/{c4Diagram-XDPPPE54-B0RBwxgS.js → c4Diagram-XDPPPE54-DH-55ik1.js} +2 -2
- package/dist/assets/assets/channel-bSjoaDB4.js +2 -0
- package/dist/assets/assets/{chunk-2E7WHVMD-xslt64yZ.js → chunk-2E7WHVMD-CtD9IAQe.js} +2 -2
- package/dist/assets/assets/{chunk-4EMNKR2T-f3IpLd1J.js → chunk-4EMNKR2T-BlWBPhJT.js} +2 -2
- package/dist/assets/assets/{chunk-55XCU76K-D3q6AZAA.js → chunk-55XCU76K-CLbB5lqy.js} +2 -2
- package/dist/assets/assets/{chunk-7S6XSTFO-CaV-HpLf.js → chunk-7S6XSTFO-D33yaufg.js} +2 -2
- package/dist/assets/assets/{chunk-AQDTSKZB-DbOv8phx.js → chunk-AQDTSKZB-PRYBX44u.js} +2 -2
- package/dist/assets/assets/{chunk-DSNLSHJZ-CGoIJL3I.js → chunk-DSNLSHJZ-CyfThOqM.js} +2 -2
- package/dist/assets/assets/{chunk-HAGFOTED-K0-xCmev.js → chunk-HAGFOTED-DzN80Tcl.js} +2 -2
- package/dist/assets/assets/{chunk-HNE4Q36P-C3I77Xwt.js → chunk-HNE4Q36P-DKoC-RgY.js} +2 -2
- package/dist/assets/assets/{chunk-NQOKRVIF-r8UsQoSM.js → chunk-NQOKRVIF-BLXN1l5s.js} +2 -2
- package/dist/assets/assets/{chunk-UHW7PFBP-DWmOTjfa.js → chunk-UHW7PFBP-CtkUl02Z.js} +2 -2
- package/dist/assets/assets/{chunk-VQ5W62QI-CJV5dZLW.js → chunk-VQ5W62QI-DcSOZjGK.js} +2 -2
- package/dist/assets/assets/{chunk-WQQL4CDK-Bfpg87o7.js → chunk-WQQL4CDK-aN1-PJ3t.js} +2 -2
- package/dist/assets/assets/chunk-XXDRQBXY-BIzpIYaa.js +2 -0
- package/dist/assets/assets/{chunk-YZO67HFG-Cf0ywi0D.js → chunk-YZO67HFG-DhtQKpcb.js} +2 -2
- package/dist/assets/assets/{chunk-ZAUX2LTX-iC5Tn6mf.js → chunk-ZAUX2LTX-BKRwwtRo.js} +2 -2
- package/dist/assets/assets/{chunk-ZCHMQSOR-DLvEBxTv.js → chunk-ZCHMQSOR-BZT1wRxe.js} +2 -2
- package/dist/assets/assets/{classDiagram-v2-4MYWR3UA-DjsXLyQa.js → classDiagram-v2-4MYWR3UA-CMWkILSY.js} +2 -2
- package/dist/assets/assets/{cose-bilkent-JH36ORCC-Dyl7fgJO.js → cose-bilkent-JH36ORCC-Dar4SYjM.js} +2 -2
- package/dist/assets/assets/{cynefin-EF2NZ3EQ-CCTTt4il.js → cynefin-EF2NZ3EQ-Dh1r-XyN.js} +1 -1
- package/dist/assets/assets/{cynefinDiagram-WF24UDRP-djxzhWm0.js → cynefinDiagram-WF24UDRP-Dv7zKVsq.js} +2 -2
- package/dist/assets/assets/{dagre-NK4GIZVX-CIY5ZJbh.js → dagre-NK4GIZVX-Bf9qZfJX.js} +2 -2
- package/dist/assets/assets/{diagram-CBK3MWTC-LaFd7Qht.js → diagram-CBK3MWTC-Ca4NIw3-.js} +2 -2
- package/dist/assets/assets/{diagram-I5XIIV2D-Dk5ZMZfF.js → diagram-I5XIIV2D-DR1tHQSH.js} +2 -2
- package/dist/assets/assets/{diagram-ODIL2UCW-DN26_SkT.js → diagram-ODIL2UCW-Bja9G_fP.js} +2 -2
- package/dist/assets/assets/{diagram-PFBEJUXE-DheR717B.js → diagram-PFBEJUXE-CcKrvx7F.js} +2 -2
- package/dist/assets/assets/{diagram-RJA3I4VV-DX5eWt50.js → diagram-RJA3I4VV-ChfUAp5c.js} +2 -2
- package/dist/assets/assets/{diagram-TYUNFSNR-CzcDrOnS.js → diagram-TYUNFSNR-Z7EIy_Dd.js} +2 -2
- package/dist/assets/assets/{dist-DMawibLu.js → dist-C5b3-Ra2.js} +2 -2
- package/dist/assets/assets/{dist-BxOg0kfS.js → dist-C8ca3uHq.js} +2 -2
- package/dist/assets/assets/{dist-Baxx78b8.js → dist-CB7zR0aj.js} +2 -2
- package/dist/assets/assets/{dist-D-4bVX5R.js → dist-CY2drnbW.js} +2 -2
- package/dist/assets/assets/{dist-phEYiQPT.js → dist-CeHA3RMV.js} +2 -2
- package/dist/assets/assets/{dist-BguOTt2C.js → dist-CnDVRyzg.js} +2 -2
- package/dist/assets/assets/{dist-DgyHiiLg.js → dist-D4ABsHNx.js} +2 -2
- package/dist/assets/assets/{dist-Fr_cVur6.js → dist-DkzTnMW6.js} +2 -2
- package/dist/assets/assets/{dist-BmdHJeNc.js → dist-pvEcNix9.js} +2 -2
- package/dist/assets/assets/{ebnfDiagram-V4P3TTPT-CoM013pL.js → ebnfDiagram-V4P3TTPT-Cj7VJ0V4.js} +2 -2
- package/dist/assets/assets/{elk-QONTBCTQ-DmGjc9Hh.js → elk-QONTBCTQ-0md1Ryrf.js} +2 -2
- package/dist/assets/assets/{erDiagram-KYQIGQAA-Dz3-bYVx.js → erDiagram-KYQIGQAA-DtERkMAJ.js} +2 -2
- package/dist/assets/assets/{eventmodeling-K75KTNOO-CLlxLv2A.js → eventmodeling-K75KTNOO-CSIPK-Eo.js} +1 -1
- package/dist/assets/assets/flowDiagram-IUGLLWBU-B9oPI3Eh.js +1 -0
- package/dist/assets/assets/{ganttDiagram-R7GPNTJY-DnUTi2Lw.js → ganttDiagram-R7GPNTJY-WODJvYlC.js} +2 -2
- package/dist/assets/assets/{gitGraph-VSP46ZUC-BKN2dqtq.js → gitGraph-VSP46ZUC-u62VUFlC.js} +1 -1
- package/dist/assets/assets/{gitGraphDiagram-PDYL7XHY-DLrrvd0J.js → gitGraphDiagram-PDYL7XHY-nliEw829.js} +2 -2
- package/dist/assets/assets/index-BlFg3Cgj.js +200 -0
- package/dist/assets/assets/index-CWkfd_A-.css +1 -0
- package/dist/assets/assets/{info-OHQRW6UA-BDEgHbYs.js → info-OHQRW6UA-CYikzsdB.js} +1 -1
- package/dist/assets/assets/{infoDiagram-MVDRKAX5-C3Nf12JT.js → infoDiagram-MVDRKAX5-CAW8nciZ.js} +2 -2
- package/dist/assets/assets/{ishikawaDiagram-HPEHV2GE-fbHmqACp.js → ishikawaDiagram-HPEHV2GE-CfEaOuah.js} +2 -2
- package/dist/assets/assets/{journeyDiagram-BOSHW7O7-BFGkRISm.js → journeyDiagram-BOSHW7O7-gQ-SjkNw.js} +2 -2
- package/dist/assets/assets/{kanban-definition-FNSA4HC5-CT8LXXjC.js → kanban-definition-FNSA4HC5-DMD23QWj.js} +2 -2
- package/dist/assets/assets/{line-DNJRN0fU.js → line-BqPW5Rca.js} +2 -2
- package/dist/assets/assets/{linear-o7QEED__.js → linear-Gt3NZtDp.js} +2 -2
- package/dist/assets/assets/{mermaid-parser.core-CqEUiMwG.js → mermaid-parser.core-jr9WuLKp.js} +4 -4
- package/dist/assets/assets/{mermaid.core-UmrHaJ93.js → mermaid.core-nONZH9ES.js} +5 -5
- package/dist/assets/assets/{mindmap-definition-6OY57UG3-1CWvf4XD.js → mindmap-definition-6OY57UG3-P0G1aSZ_.js} +2 -2
- package/dist/assets/assets/{packet-JDAUHWVQ-DADADHfZ.js → packet-JDAUHWVQ-BRYh19T9.js} +1 -1
- package/dist/assets/assets/{pegDiagram-ECIUJNBX-QahCrnnP.js → pegDiagram-ECIUJNBX-DVXvDw5m.js} +2 -2
- package/dist/assets/assets/{pie-XZMESJXO-CcVs8yjR.js → pie-XZMESJXO-C4zblXYs.js} +1 -1
- package/dist/assets/assets/{pieDiagram-GNMPY74T-IVVcmoj4.js → pieDiagram-GNMPY74T-DQZMSxzU.js} +2 -2
- package/dist/assets/assets/{quadrantDiagram-D57K4MC3-CS7f-VeJ.js → quadrantDiagram-D57K4MC3-CoJW9FbN.js} +2 -2
- package/dist/assets/assets/{radar-ABXABTNO-imva_GNF.js → radar-ABXABTNO-C1hflkM-.js} +1 -1
- package/dist/assets/assets/{railroad-I3PHUGI6-GitT3taK.js → railroad-I3PHUGI6-BWfPWtIx.js} +1 -1
- package/dist/assets/assets/{railroad-abnf-LNEFI6M7-DA9a4ok6.js → railroad-abnf-LNEFI6M7-ZD-V0lbr.js} +1 -1
- package/dist/assets/assets/{railroad-ebnf-DWYD2UWJ-2G9UuZV0.js → railroad-ebnf-DWYD2UWJ-101vSltK.js} +1 -1
- package/dist/assets/assets/{railroad-peg-JR7BVNR7-KGkhk5i6.js → railroad-peg-JR7BVNR7-C2qdCoeJ.js} +1 -1
- package/dist/assets/assets/{railroadDiagram-Y72NRBL7-DRwAClPI.js → railroadDiagram-Y72NRBL7-CVB1kO7b.js} +2 -2
- package/dist/assets/assets/{requirementDiagram-EQYSW5RA-CWcrJ4Kd.js → requirementDiagram-EQYSW5RA-D2U3nwPk.js} +2 -2
- package/dist/assets/assets/{sankeyDiagram-SY24JHO5-CkMOBlFF.js → sankeyDiagram-SY24JHO5-CKjkT8B_.js} +2 -2
- package/dist/assets/assets/{sequenceDiagram-BLEHNHQU-B10XOG3r.js → sequenceDiagram-BLEHNHQU-CwVqG2fG.js} +2 -2
- package/dist/assets/assets/{src-BpxERY-4.js → src-bIf72vcz.js} +2 -2
- package/dist/assets/assets/{stateDiagram-v2-A6IESKWZ-D50RKXhB.js → stateDiagram-v2-A6IESKWZ-97EIvkg9.js} +2 -2
- package/dist/assets/assets/{swimlanes-B3ENRKFQ-DlFQGv2L.js → swimlanes-B3ENRKFQ-D9egyUg3.js} +2 -2
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BkS3IR0c.js +9 -0
- package/dist/assets/assets/{timeline-definition-JXYKGLGB-B3Sb86Ee.js → timeline-definition-JXYKGLGB-CbG0LH-D.js} +2 -2
- package/dist/assets/assets/{treeView-D4JQ5SDB-C0RfpNmP.js → treeView-D4JQ5SDB-COfpvikT.js} +1 -1
- package/dist/assets/assets/{treemap-SAJKECNS-DEYe7AgT.js → treemap-SAJKECNS-CU-jFNpR.js} +1 -1
- package/dist/assets/assets/{usecaseDiagram-WPOLBNNX-D--b6tnm.js → usecaseDiagram-WPOLBNNX-BGnYi9SF.js} +2 -2
- package/dist/assets/assets/{vennDiagram-Q3Y3IDCW-D1TkV4xk.js → vennDiagram-Q3Y3IDCW-Cb4zd6ET.js} +2 -2
- package/dist/assets/assets/{wardley-7MLQ67FV-BW1rHoM4.js → wardley-7MLQ67FV-ULAC2YGd.js} +1 -1
- package/dist/assets/assets/{wardleyDiagram-IVAIDKWA-1eGu-wA2.js → wardleyDiagram-IVAIDKWA-Bi-y7zjP.js} +2 -2
- package/dist/assets/assets/{webpack-BxGI2QQO.js → webpack-eZcyXM6S.js} +2 -2
- package/dist/assets/assets/{xychartDiagram-4URNHDU4-Brc-3D_H.js → xychartDiagram-4URNHDU4-BvTZJqeU.js} +2 -2
- package/dist/assets/bundle-asset-policy.json +1 -1
- package/dist/assets/index.html +2 -2
- package/dist/assets/plugins/assets/base-Bz0oeehA.css +2 -0
- package/dist/assets/plugins/chunks/po-web-runtime-oroB3Znq.js +1 -0
- package/dist/assets/plugins/compositions.json +1 -1
- package/dist/assets/plugins/slots/approval.72ae703a-DFWTk7Ap.js +2 -0
- package/dist/assets/plugins/slots/artifacts.77a5ce89--B-D-lue.js +1 -0
- package/dist/assets/plugins/slots/author.1c902d5c--QQ4lLeg.js +93 -0
- package/dist/assets/plugins/slots/{autocompact.86aeccf4-CcvIN-cI.js → autocompact.f08b6833-BZ-Hd0ei.js} +1 -1
- package/dist/assets/plugins/slots/browse.a8452a8d-DekLuc-Z.js +1 -0
- package/dist/assets/plugins/slots/{builtin-tools.0a7f0b8e-kbo97l14.js → builtin-tools.abc3edcc-zeBI1cKp.js} +3 -3
- package/dist/assets/plugins/slots/codemode.c68822dc-HLrDhndJ.js +11 -0
- package/dist/assets/plugins/slots/domain.d3fc60b5-Dwn3GboM.js +1 -0
- package/dist/assets/plugins/slots/{edit.c5b0b072-D5UaJjPf.js → edit.2aa43041-CddVpEel.js} +3 -3
- package/dist/assets/plugins/slots/files.c1e584ee-DxOpzqm3.js +2 -0
- package/dist/assets/plugins/slots/goal.b1d8b03b-C9tmOreI.js +1 -0
- package/dist/assets/plugins/slots/grep.b067b8cb-C4OjbSn9.js +1 -0
- package/dist/assets/plugins/slots/help.3b3e56cb-CcgpN98Q.js +3 -0
- package/dist/assets/plugins/slots/log.24faf8a0-BtnnodkX.js +4 -0
- package/dist/assets/plugins/slots/mcp.a6805ffa-DrBGkASK.js +109 -0
- package/dist/assets/plugins/slots/plan.19d1704d-C3Tml2Sz.js +3 -0
- package/dist/assets/plugins/slots/profile.1b4aeee4-1K7Wt9AD.js +1 -0
- package/dist/assets/plugins/slots/{prompts.2c187969-C4F2-Qgt.js → prompts.a5509377-h93o8dcF.js} +2 -2
- package/dist/assets/plugins/slots/read.a43eeb4a-DNoCGY1k.js +1 -0
- package/dist/assets/plugins/slots/runner.03b699da-DGs8HywA.js +8 -0
- package/dist/assets/plugins/slots/sessions.dc7ce5f8-CwbzOt92.js +1 -0
- package/dist/assets/plugins/slots/{skill.f5396fde-DjLYO2JJ.js → skill.2b6ba429-6Lp0cyos.js} +2 -2
- package/dist/assets/plugins/slots/subagents.9adbe0d5-tX_I8uwl.js +7 -0
- package/dist/assets/plugins/slots/vault.593b32bd-dkDWzchJ.js +1 -0
- package/dist/assets/plugins/slots/voice.376a066c-Clktk2zw.js +1 -0
- package/dist/{server-D9MvODKo.js → server-D0Pm5Cv2.js} +119 -6
- package/dist/worker.js +54 -37
- package/package.json +39 -39
- package/dist/assets/assets/channel-DNl1jI1M.js +0 -2
- package/dist/assets/assets/chunk-XXDRQBXY-3eapdwCn.js +0 -2
- package/dist/assets/assets/flowDiagram-IUGLLWBU-BFT5SBcS.js +0 -1
- package/dist/assets/assets/index-CcUcRF1S.css +0 -1
- package/dist/assets/assets/index-DWONOipn.js +0 -200
- package/dist/assets/assets/swimlanesDiagram-AYQRV4AK-BYHWhExM.js +0 -9
- package/dist/assets/plugins/assets/base-LmdY6uBA.css +0 -2
- package/dist/assets/plugins/chunks/po-web-runtime-DtS_FP_f.js +0 -1
- package/dist/assets/plugins/slots/approval.dd60ec90-m-Ra7Ebe.js +0 -2
- package/dist/assets/plugins/slots/artifacts.a078f1a5-DTv8TGH0.js +0 -1
- package/dist/assets/plugins/slots/author.497633d0-COLvE24q.js +0 -93
- package/dist/assets/plugins/slots/browse.5fcf164c-BgK_ibjS.js +0 -1
- package/dist/assets/plugins/slots/codemode.ff16ac06-CXHWhJc8.js +0 -11
- package/dist/assets/plugins/slots/domain.3ddea842-CvZmPWdh.js +0 -1
- package/dist/assets/plugins/slots/files.8ffcdcc0-COYaael1.js +0 -2
- package/dist/assets/plugins/slots/goal.423c7a26-nmfrCrdh.js +0 -1
- package/dist/assets/plugins/slots/grep.95f470b3-osJU0D9d.js +0 -1
- package/dist/assets/plugins/slots/help.03b9ba99-BZU2hmYF.js +0 -3
- package/dist/assets/plugins/slots/log.19bda339-Bi7himlR.js +0 -4
- package/dist/assets/plugins/slots/mcp.ffbe405a-aEn779DD.js +0 -109
- package/dist/assets/plugins/slots/plan.5eac6563-B8M9sD_u.js +0 -3
- package/dist/assets/plugins/slots/profile.176710dd-C38rbDGj.js +0 -1
- package/dist/assets/plugins/slots/read.1629d556-Bh5_twoW.js +0 -1
- package/dist/assets/plugins/slots/runner.962030e5-B4S52R79.js +0 -8
- package/dist/assets/plugins/slots/sessions.fc763f42-Dr4py-zv.js +0 -1
- package/dist/assets/plugins/slots/subagents.d815a296-Dew0ZskW.js +0 -7
- package/dist/assets/plugins/slots/vault.57fd9047-C0rZL_dc.js +0 -1
- package/dist/assets/plugins/slots/voice.b709d05c-DonnEXWO.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$t as e,Bn as t,Br as n,Cn as r,Cr as i,En as a,Er as o,F as s,Fn as c,G as l,I as u,In as d,Ir as f,J as p,Jn as m,K as h,Ln as g,Lr as _,M as v,N as y,P as b,Pr as x,Q as S,R as C,Rn as w,Rt as T,T as E,Tr as ee,Vn as te,Wn as ne,Z as re,_r as ie,a as ae,d as oe,ft as D,g as O,gr as se,h as k,hn as ce,i as A,j as le,jr as ue,kr as de,n as fe,nn as pe,o as j,q as me,r as he,s as M,un as ge,wr as N,yr as _e,zn as ve}from"../chunks/po-web-runtime-oroB3Znq.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:de(void 0),activeSession:N(null),handoff:N(void 0),browserState:N(void 0),realtimeControls:N(void 0),switchPending:N(void 0),runtime:N(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,he())&&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,he())&&($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=se(ft,{scopes:[`host`,`workspace`,`session`],basePath:`voice`,transport:(e,t)=>fe.fetch(e,t),sessionAddress:n}),U=se(ft,{scopes:[`host`,`workspace`,`session`],basePath:`voice-media`,transport:(e,t)=>fe.fetch(e,t),sessionAddress:n}),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:t,takeOver:n,retry:r,mute:i,end:a,pending:o,error:s}){let c=t.kind===`deviceLive`,l=t.kind===`standby`,u=t.ownerName??`another device`;return M(`section`,{"aria-label":`Voice`,className:`flex flex-col gap-3`,children:[j(`h3`,{className:`text-lg font-semibold text-po-hi`,children:`Voice`}),M(`div`,{className:`flex items-center gap-2`,children:[j(ne,{tone:c?`cyan`:l?`muted`:`magenta`}),j(`span`,{className:`text-base font-semibold text-po-hi`,children:l?`Voice is on standby`:c?`Live on this device`:`Voice is active on ${u}`})]}),j(`p`,{className:`text-sm leading-relaxed text-po-dim`,children:l?`Another window on this device is using voice. This window is not listening.`:c?`${t.deviceName??`This device`} · Microphone live. Other devices can run their own Live conversations separately.`:t.kind===`stale`?`Voice moved since you last checked. Take over from ${u} whenever you are ready.`:`This device is not listening. You can move this session’s voice here whenever you are ready.`}),t.kind===`conflict`||t.kind===`stale`?j(`div`,{children:j(e,{variant:`secondary`,disabled:o||!n,onClick:n,children:`Take over`})}):c?M(`div`,{className:`flex gap-2`,children:[j(e,{variant:`subtle`,disabled:o||!i,onClick:i,children:`Mute`}),j(e,{variant:`subtle`,disabled:o||!a,onClick:a,children:`End Live on this device`})]}):null,c?j(`p`,{className:`text-sm text-po-dim`,children:`Each device’s Live conversation is billed separately.`}):null,s?j(`p`,{role:`alert`,className:`text-sm text-po-red`,children:s}):null,s&&r?j(`div`,{children:j(e,{variant:`subtle`,disabled:o,onClick:r,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 j(`span`,{"aria-hidden":!0,className:`flex h-3 items-end gap-[2px]`,children:[3,7,5,9,4].map((t,n)=>j(`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:t,onClick:n,pending:r,...i}){return n===void 0?null:j(e,{variant:`subtle`,size:`xs`,disabled:r,onClick:n,...i,children:t})}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:t,picker:n,actions:r,pending:i,error:a,ownership:o,ownershipActions:s}){if(o)return j(xt,{state:o,takeOver:s?.takeOver,retry:s?.retry,mute:r.mute,end:r.end,pending:i,error:a});let c=Et(t),l=t.kind===`daily`&&t.view.microphoneMuted,u=t.kind===`live`&&t.realtime?.muted===!0,d=l||u?`unmute`:`mute`,f=t.kind===`live-failed`,p=t.kind===`daily`&&t.signInHint;return M(`div`,{"data-testid":`voice-activity`,"data-voice-phase":c.phase,className:`flex flex-col gap-2 px-1`,children:[n===void 0?null:M(re,{"aria-label":`Voice for this session`,value:n.value,disabled:n.disabled||i,onValueChange:e=>n.onPick(e),className:`grid grid-cols-2 gap-1.5`,children:[j(S,{value:`live`,"data-testid":`voice-pick-live`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Live`}),j(S,{value:`legacy`,"data-testid":`voice-pick-legacy`,className:`px-2 py-1 text-center text-sm font-medium text-po-hi`,children:`Daily work`})]}),M(`span`,{className:`flex min-w-0 items-center gap-2`,children:[j(ne,{tone:St[c.tone],pulse:c.pulse}),j(`span`,{"data-testid":`voice-label`,className:`flex-1 truncate text-base font-semibold ${Ct[c.tone]}`,children:c.label}),c.elapsed?j(`span`,{"data-testid":`voice-elapsed`,className:`shrink-0 text-sm tabular-nums text-po-yellow`,children:c.elapsed}):null,c.meter?j(wt,{tone:c.tone}):null]}),t.kind===`daily`||t.kind===`live`?M(`span`,{className:`flex flex-wrap gap-1.5`,children:[j(W,{label:d,onClick:r.mute,pending:i,"aria-pressed":l||u,...t.kind===`daily`?{"data-testid":`voice-autonomous-microphone-toggle`,"aria-label":`${d} autonomous voice microphone`,title:`${d} autonomous voice microphone`}:{}}),j(W,{label:`interrupt`,onClick:t.kind===`live`?r.interrupt:void 0,pending:i,title:`Interrupt local output. Output stays silent until this realtime session ends.`}),j(W,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,c.detail&&!p?j(`span`,{"data-testid":`voice-detail`,role:f?`alert`:void 0,className:`text-sm leading-relaxed text-po-dim`,children:f&&r.useDailyWork!==void 0?`${c.detail} You can keep talking with daily work.`:c.detail}):null,p?M(`span`,{className:`flex flex-col items-start gap-2`,children:[j(`span`,{"data-testid":`voice-sign-in-hint`,className:`text-sm leading-relaxed text-po-dim`,children:`live needs your ChatGPT for Po features sign-in. Daily work keeps listening meanwhile.`}),r.signIn===void 0?null:j(e,{variant:`secondary`,size:`xs`,"data-testid":`voice-sign-in`,onClick:r.signIn,children:`sign in`})]}):null,f?M(`span`,{className:`flex flex-wrap gap-1.5`,children:[j(W,{label:`use daily work`,onClick:r.useDailyWork,pending:i,"data-testid":`voice-use-daily`}),j(W,{label:`end`,onClick:r.end,pending:i,"data-testid":`voice-end`})]}):null,t.kind===`live-elsewhere`||t.kind===`daily-elsewhere`?j(`span`,{className:`flex`,children:j(W,{label:t.kind===`live-elsewhere`?`move Live here`:`move daily work here`,onClick:t.kind===`live-elsewhere`?r.routeLiveHere:r.moveDailyWorkHere,pending:i,"data-testid":t.kind===`live-elsewhere`?`voice-global-live-transfer`:`voice-daily-move`})}):null,a===null?null:j(`span`,{role:`alert`,className:`text-sm leading-relaxed text-po-yellow`,children:a})]})}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;oe(()=>{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 ie(`end`),await E(`activate`,`legacy`)}),ie=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(()=>ie(`end`)),D={},se,k=(t,n,r=!1)=>{e!==null&&v&&(se={value:n,disabled:r,onPick:t})};switch(w.kind){case`switching`:k(()=>void 0,w.mode,!0);break;case`daily`:if(e===null)break;k(e=>void(e===`live`?ne():void 0),`legacy`),i.phase!==`starting`&&i.phase!==`draining`&&(D.mute=()=>void T(()=>E(i.microphoneMuted?`unmute`:`mute`))),D.end=()=>void T(()=>E(`deactivate`)),n&&(D.signIn=()=>n(`providers`));break;case`live`:{let e=w.realtime?.muted===!0;k(e=>void(e===`legacy`?re():void 0),`live`),D.mute=()=>C?C.mute(!e):void T(()=>ie(e?`unmute`:`mute`)),D.interrupt=()=>C?C.interrupt():void T(()=>ie(`interrupt`)),D.end=ae;break}case`live-failed`:k(e=>void(e===`legacy`?re():void 0),`live`),e!==null&&(D.useDailyWork=()=>void re()),D.end=ae;break;case`live-elsewhere`:k(()=>void 0,`live`,!0),e!==null&&(D.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`:k(()=>void 0,`legacy`,!0),e!==null&&(D.moveDailyWorkHere=()=>void T(()=>E(`activate`,`legacy`)))}let ce=a?.sessionId===e||a?.sessionId===null?a:void 0;return j(Dt,{state:w,picker:se,actions:D,pending:l,error:d,ownership:ce?.ownership,ownershipActions:ce?.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:j(kt,{...e})}var jt=i({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]??=N({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:he()});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)=>fe.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 fe.fetch(t,n);let r=new Headers(n.headers),i=Oe({header:he()});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=fe.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:he()}),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=f(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=ue({...Wr,icon:u}),Kr=ue({...Wr,icon:u}),qr=ie({name:`voice`,keys:`v e`,statusKey:`po-voice`,activeSource:nt,hideWhenEmpty:!0,marksBackgroundWork:!1,placement:`bottom`,order:60}),Jr=_e(it),Yr=_e(at),Xr=i({data:rt}),Zr=i({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 M(l,{open:e!==void 0,onOpenChange:e=>{e||t()},children:[j(h,{asChild:!0,children:n}),M(p,{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:[j(m,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),j(`span`,{className:`min-w-0 flex-1 break-words`,children:e}),j(me,{"aria-label":`dismiss`,className:`shrink-0 rounded-sm p-0.5 hover:bg-po-tint-red`,children:j(a,{"aria-hidden":!0,className:`size-3.5`})})]})]})}function mi({sessionId:t,appendComposerDraft:n,statuses:r,registeredMinorModes:i}){let a=A(R.store,e=>e),o=A(z.store),s=bt(r[`po-voice`]),[c,l]=O({phase:`idle`}),d=k(void 0);d.current??=new di(n,()=>{l(d.current?.snapshot()??{phase:`idle`})});let f=c.phase,p=c.error,h=o?.sessionId===null&&o.realtime!==void 0&&o.realtime.connection!==`closed`,g=s.mode===`auto`||s.mode===`live`||a!==null||h;oe(()=>{let e=d.current;return()=>e?.dispose()},[]),oe(()=>{d.current?.setAppend(n)},[n]),oe(()=>{d.current?.reset()},[t,g]);let _=()=>{g||d.current?.toggle(t)},v=!g&&f===`recording`,y=g?fi:p??(v?`stop voice recording and fill the prompt`:f===`transcribing`?`transcribing voice recording`:f===`starting`?`starting voice recording`:`start voice recording`),b=g?`blocked`:f,x=p&&!g?`text-po-red`:`text-po-dim`;return i?.includes(`voice-auto`)?j(pi,{error:g?void 0:p,onDismiss:()=>d.current?.reset(),children:j(e,{variant:v?`danger-outline`:`ghost`,size:`icon-md`,"data-testid":`composer-voice-action`,"data-voice-mode":g?`auto`:v?`manual`:`off`,"data-voice-phase":b,"aria-label":y,title:y,disabled:t===null||g||f===`starting`||f===`transcribing`,onClick:_,className:`shrink-0 ${x}`,children:v?j(T,{className:`size-3 fill-current`}):f===`starting`||f===`transcribing`?j(E,{className:`size-4 animate-spin`}):j(p&&!g?m:u,{className:`size-4`})})}):null}var hi=i({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:n,choice:r}=A(K.store,e=>e),[i,a]=O(0);if(r===void 0)return null;let o=gi(n),s=i<o.length?i:0,l=e=>{let t=n[o.indexOf(e)];t!==void 0&&r(t.deviceId,!0)};return j(c,{open:!0,onOpenChange:e=>{e||r(null,!1)},children:M(g,{width:`sm`,"data-testid":`voice-microphone-dialog`,"aria-describedby":void 0,onKeyDown:e=>ge(e,{options:o,cursor:s,onCursorChange:a,onSelect:l}),children:[j(t,{children:j(te,{children:`choose a microphone`})}),M(d,{children:[j(w,{children:`autonomous voice found more than one input. this browser remembers the one you pick.`}),j(C,{options:o,cursor:s,onCursorChange:a,onSelect:l,testIdPrefix:`voice-microphone-option`}),M(ve,{className:`flex-col items-stretch`,children:[M(`span`,{className:`w-full text-sm text-po-dim`,children:[ce(o.length),` · esc uses the browser default once`]}),j(e,{variant:`outline`,size:`md`,"data-testid":`voice-microphone-default`,onClick:()=>r(null,!0),children:`always use browser default`})]})]})]})})}var vi=i({slot:`overlay`,id:`voice`,component:_i}),yi=ee({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=f(Hr),xi=o({name:`voice`,modeId:`voice-auto`,keys:`v e`,icon:u,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:e,args:t,result:n,running:i,isError:a}){if(e===`narrate`){let e=na(t);return M(`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:[j(pe,{"aria-hidden":`true`,className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-po-magenta`}),j(`p`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:e||`Narration unavailable.`})]})}let o=Bi(e,t),c=ia(e,n,{expanded:!1,isError:a,isPartial:i}),l=ia(e,n,{expanded:!0,isError:a,isPartial:i}),u=ta(e,n,{expanded:!1,isError:a,isPartial:i}),d=a?ra(n):``;return j(le,{tone:r({running:i,isError:a}),expandable:!a&&l.length>c.length,children:({expanded:t})=>M(ae,{children:[j(y,{title:e,children:M(`span`,{"data-testid":`tool-call-${e}`,className:`flex min-w-0 flex-1 items-center gap-2`,children:[M(`span`,{className:`shrink-0 font-semibold text-po-hi`,children:[o.glyph,` `,o.action]}),o.detail?j(`span`,{className:`min-w-0 truncate ${o.detailIsName?`text-po-blue`:`text-po-dim`}`,children:o.detail}):null]})}),a?d.length>0?j(v,{"data-testid":`tool-result-${e}`,children:j(`p`,{className:`whitespace-pre-wrap break-words text-po-red`,children:d})}):null:j(v,{"data-testid":`tool-result-${e}`,children:i&&n===null?j(b,{tone:`running`,children:`running`}):u.kind===`status`?j(sa,{status:u.status}):u.kind===`fields`?j(ca,{fields:u.fields}):j(s,{lines:t?l:c})})]})})}var oa={active:`green`,pending:`yellow`,idle:`neutral`};function sa({status:e}){return M(`div`,{className:`flex flex-col gap-2`,children:[M(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[j(D,{tone:oa[e.phase],children:`voice ${e.state}`}),j(D,{tone:`blue`,children:`mode ${e.mode}`}),j(D,{tone:e.muted?`yellow`:`neutral`,children:e.muted?`mic muted`:`mic on`}),e.manual===void 0?null:j(D,{children:`dictation ${e.manual}`})]}),e.error===void 0?null:j(`p`,{className:`break-words text-po-red`,children:e.error})]})}function ca({fields:e}){return e.length===0?j(`p`,{className:`text-po-faint`,children:`No result details.`}):j(`dl`,{className:`grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-4 gap-y-0.5`,children:e.map(e=>M(`div`,{className:`contents`,children:[j(`dt`,{className:`truncate text-po-dim`,children:e.key}),j(`dd`,{className:`break-words text-po-text`,children:e.value})]},e.key))})}var la=x({tools:[wi],timelinePresentation:`message`,message:aa}),ua=x({tools:[Si,Ci,Ti],message:aa}),$=(e,t)=>t===void 0?void 0:{...e,...t},da=_({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};
|
|
@@ -5,7 +5,7 @@ import "./exports-CgYBL1bW.js";
|
|
|
5
5
|
import { n as readPackageResource, t as packageResourcePath } from "./index.edge-CDBGyAxt.js";
|
|
6
6
|
import { i as isUnattended, n as gateApproval, o as PO_APPROVAL_SERVICE, s as readPoApproval, t as ApprovalPendingError } from "./approval-DSfCC4gB.js";
|
|
7
7
|
import { a as PO_BACKGROUND_WORK_SERVICE, l as readPoBackgroundWorkService } from "./backgroundWork-DCAXx7Rj.js";
|
|
8
|
-
import { c as defineRoot, f as defineServerTool, n as composeRootInjects, s as defineResource, t as composeRootHooks } from "./extensionFile-H7Bjt9rF.js";
|
|
8
|
+
import { c as defineRoot, d as defineServerCommand, f as defineServerTool, n as composeRootInjects, r as defineChannel, s as defineResource, t as composeRootHooks } from "./extensionFile-H7Bjt9rF.js";
|
|
9
9
|
import { r as assertCodemodeNamespaceName, t as PO_CODEMODE_CONTRACT } from "./codemode-BGg_bdyR.js";
|
|
10
10
|
import "./majorModes-CNeGE-W8.js";
|
|
11
11
|
import path from "node:path";
|
|
@@ -1038,6 +1038,12 @@ const Meta = {
|
|
|
1038
1038
|
}
|
|
1039
1039
|
};
|
|
1040
1040
|
//#endregion
|
|
1041
|
+
//#region ../../default/po-codemode/src/constants/backgroundScripts.ts
|
|
1042
|
+
/** The hub channel frame carrying one session's running background scripts. */
|
|
1043
|
+
const CODEMODE_BACKGROUND_TYPE = "codemode_background";
|
|
1044
|
+
/** The slash command the page sends to stop one background script. */
|
|
1045
|
+
const CODEMODE_STOP_COMMAND = "background-scripts-stop";
|
|
1046
|
+
//#endregion
|
|
1041
1047
|
//#region ../../default/po-codemode/src/services/codemodeRegistry/index.ts
|
|
1042
1048
|
/** Dot-separated segments without whitespace, so names such as `my-server.create-issue` can be gated. */
|
|
1043
1049
|
const MEMBER_PATH = /^[^.\s]+(?:\.[^.\s]+)*$/u;
|
|
@@ -1325,9 +1331,14 @@ const MAX_LISTED_SCRIPTS = 20;
|
|
|
1325
1331
|
const MAX_IMAGES = 4;
|
|
1326
1332
|
const MAX_IMAGE_BYTES = 5242880;
|
|
1327
1333
|
const DEFAULT_IMAGE_MIME = "image/png";
|
|
1334
|
+
const MAX_SCRIPT_LABEL = 200;
|
|
1328
1335
|
const MEMBER_LINE = /^\s{2}(?:readonly\s+)?(\w+)\s*[(?:<]/u;
|
|
1329
1336
|
const GLOBALS_HELP = "Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). Return a value with `return`.";
|
|
1330
1337
|
const SCRIPTS_HELP = "Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; inside it, `args` is the argument and its `return` is the result.";
|
|
1338
|
+
/** The script's first non-empty line, so two scripts can be told apart. */
|
|
1339
|
+
function scriptLabel(code) {
|
|
1340
|
+
return (code.split("\n").find((candidate) => candidate.trim() !== "") ?? "").trim().slice(0, MAX_SCRIPT_LABEL);
|
|
1341
|
+
}
|
|
1331
1342
|
function text(value, isError = false) {
|
|
1332
1343
|
return {
|
|
1333
1344
|
content: [{
|
|
@@ -1936,6 +1947,8 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
|
|
|
1936
1947
|
const job = {
|
|
1937
1948
|
id,
|
|
1938
1949
|
sessionId: execution.sessionId,
|
|
1950
|
+
label: scriptLabel(parameters.code),
|
|
1951
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1939
1952
|
controller,
|
|
1940
1953
|
status: "running",
|
|
1941
1954
|
done: Promise.resolve()
|
|
@@ -2001,6 +2014,14 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
|
|
|
2001
2014
|
};
|
|
2002
2015
|
}
|
|
2003
2016
|
};
|
|
2017
|
+
/** One cancel for the agent's `exec_cancel` and the page's stop control; only the owning session may stop a job. */
|
|
2018
|
+
const cancel = (sessionId, id, reason) => {
|
|
2019
|
+
const job = jobs.get(id);
|
|
2020
|
+
if (job && job.sessionId !== sessionId) return "foreign";
|
|
2021
|
+
if (job?.status !== "running") return "finished";
|
|
2022
|
+
job.controller.abort(reason ? new Error(reason) : void 0);
|
|
2023
|
+
return "stopping";
|
|
2024
|
+
};
|
|
2004
2025
|
const execCancel = {
|
|
2005
2026
|
name: "exec_cancel",
|
|
2006
2027
|
label: "Cancel Exec",
|
|
@@ -2009,15 +2030,36 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
|
|
|
2009
2030
|
mainAgentOnly: true,
|
|
2010
2031
|
executionMode: "serial",
|
|
2011
2032
|
async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
|
|
2012
|
-
const
|
|
2013
|
-
if (
|
|
2014
|
-
if (job?.status === "running") job.controller.abort(parameters.reason ? new Error(parameters.reason) : void 0);
|
|
2033
|
+
const status = cancel(execution.sessionId, parameters.id, parameters.reason);
|
|
2034
|
+
if (status === "foreign") return text("Background exec belongs to another session.", true);
|
|
2015
2035
|
return text(JSON.stringify({
|
|
2016
2036
|
id: parameters.id,
|
|
2017
|
-
status
|
|
2037
|
+
status
|
|
2018
2038
|
}));
|
|
2019
2039
|
}
|
|
2020
2040
|
};
|
|
2041
|
+
const stopCommand = {
|
|
2042
|
+
name: CODEMODE_STOP_COMMAND,
|
|
2043
|
+
description: "Stop one background code-mode script in this session by its id.",
|
|
2044
|
+
async execute(args, context) {
|
|
2045
|
+
const id = args.trim();
|
|
2046
|
+
if (!id) throw new Error(`Usage: /${CODEMODE_STOP_COMMAND} <script-id>`);
|
|
2047
|
+
const status = cancel(context.sessionId, id, "Stopped by the person.");
|
|
2048
|
+
await context.client.notify(status === "stopping" ? {
|
|
2049
|
+
body: "Stopping the background script; it reports its own end.",
|
|
2050
|
+
level: "info"
|
|
2051
|
+
} : {
|
|
2052
|
+
body: `No running background script ${id} in this session.`,
|
|
2053
|
+
level: "warning"
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
};
|
|
2057
|
+
const backgroundScripts = (sessionId) => [...jobs.values()].filter((job) => job.sessionId === sessionId).map(({ id, label, startedAt, status }) => ({
|
|
2058
|
+
id,
|
|
2059
|
+
label,
|
|
2060
|
+
startedAt,
|
|
2061
|
+
status
|
|
2062
|
+
}));
|
|
2021
2063
|
const runApproved = async (call, signal, sessionId) => {
|
|
2022
2064
|
const name = call.operation.name;
|
|
2023
2065
|
const [namespaceName, ...path] = name.split(".");
|
|
@@ -2061,6 +2103,8 @@ function createCodemodeTools({ registry, isolate, scripts, npm, fs, signal: life
|
|
|
2061
2103
|
execBackground,
|
|
2062
2104
|
execCancel,
|
|
2063
2105
|
backgroundWork,
|
|
2106
|
+
stopCommand,
|
|
2107
|
+
backgroundScripts,
|
|
2064
2108
|
runApproved,
|
|
2065
2109
|
async dispose() {
|
|
2066
2110
|
closing = true;
|
|
@@ -2570,6 +2614,10 @@ function createCodemodeSession({ context, agent, host, signal }) {
|
|
|
2570
2614
|
});
|
|
2571
2615
|
}
|
|
2572
2616
|
let background;
|
|
2617
|
+
const publishScripts = () => {
|
|
2618
|
+
if (!execution) return;
|
|
2619
|
+
host.context.directEvents?.publish(CODEMODE_BACKGROUND_TYPE, execution.sessionId, { scripts: tools.backgroundScripts(execution.sessionId) });
|
|
2620
|
+
};
|
|
2573
2621
|
const tools = createCodemodeTools({
|
|
2574
2622
|
registry,
|
|
2575
2623
|
isolate: () => readPoIsolate(context),
|
|
@@ -2577,7 +2625,10 @@ function createCodemodeSession({ context, agent, host, signal }) {
|
|
|
2577
2625
|
fs: () => readPoFs(context),
|
|
2578
2626
|
scripts,
|
|
2579
2627
|
signal,
|
|
2580
|
-
onBackgroundChange: () =>
|
|
2628
|
+
onBackgroundChange: () => {
|
|
2629
|
+
background?.update();
|
|
2630
|
+
publishScripts();
|
|
2631
|
+
},
|
|
2581
2632
|
approval: () => readPoApproval(context)
|
|
2582
2633
|
});
|
|
2583
2634
|
if (execution) context.inject([PO_APPROVAL_SERVICE], (scoped) => readPoApproval(scoped)?.registerExecutor("codemode", (call, signal) => tools.runApproved(call, signal, execution.sessionId)));
|
|
@@ -2611,6 +2662,54 @@ var root_server_default = defineRoot(root);
|
|
|
2611
2662
|
//#region ../../default/po-codemode/src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts
|
|
2612
2663
|
var codemode_server_default = defineServiceContract(PO_CODEMODE_CONTRACT.name, PO_CODEMODE_CONTRACT);
|
|
2613
2664
|
//#endregion
|
|
2665
|
+
//#region ../../default/po-codemode/src/services/backgroundScriptsChannel/index.ts
|
|
2666
|
+
function scriptsPayload(value) {
|
|
2667
|
+
return typeof value === "object" && value !== null && Array.isArray(value.scripts);
|
|
2668
|
+
}
|
|
2669
|
+
/** Relays each session's background-script snapshots, published on the direct event bus, to the page. */
|
|
2670
|
+
function createBackgroundScriptsChannel() {
|
|
2671
|
+
return {
|
|
2672
|
+
frameType: CODEMODE_BACKGROUND_TYPE,
|
|
2673
|
+
start(host) {
|
|
2674
|
+
const latest = /* @__PURE__ */ new Map();
|
|
2675
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
2676
|
+
return {
|
|
2677
|
+
payloadFor(scope) {
|
|
2678
|
+
return latest.get(scope.sessionId);
|
|
2679
|
+
},
|
|
2680
|
+
sessionAdded(scope) {
|
|
2681
|
+
subscriptions.get(scope.sessionId)?.();
|
|
2682
|
+
latest.delete(scope.sessionId);
|
|
2683
|
+
const unsubscribe = host.directEvents.subscribe(CODEMODE_BACKGROUND_TYPE, scope.sessionId, (payload) => {
|
|
2684
|
+
if (!scriptsPayload(payload)) return;
|
|
2685
|
+
latest.set(scope.sessionId, payload);
|
|
2686
|
+
host.publish(scope.sessionId, payload);
|
|
2687
|
+
}, { replayLatest: true });
|
|
2688
|
+
subscriptions.set(scope.sessionId, unsubscribe);
|
|
2689
|
+
},
|
|
2690
|
+
sessionRemoved(sessionId) {
|
|
2691
|
+
subscriptions.get(sessionId)?.();
|
|
2692
|
+
subscriptions.delete(sessionId);
|
|
2693
|
+
latest.delete(sessionId);
|
|
2694
|
+
},
|
|
2695
|
+
close() {
|
|
2696
|
+
for (const unsubscribe of subscriptions.values()) unsubscribe();
|
|
2697
|
+
subscriptions.clear();
|
|
2698
|
+
latest.clear();
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
};
|
|
2703
|
+
}
|
|
2704
|
+
//#endregion
|
|
2705
|
+
//#region ../../default/po-codemode/src/extensions/(backend)/channel/codemodeBackground.server.ts
|
|
2706
|
+
var codemodeBackground_server_default = defineChannel(function codemodeBackgroundChannel() {
|
|
2707
|
+
return createBackgroundScriptsChannel();
|
|
2708
|
+
});
|
|
2709
|
+
//#endregion
|
|
2710
|
+
//#region ../../default/po-codemode/src/extensions/workspaces/sessions/(backend)/command/background-scripts-stop.server.ts
|
|
2711
|
+
var background_scripts_stop_server_default = defineServerCommand((context) => context.root.stopCommand);
|
|
2712
|
+
//#endregion
|
|
2614
2713
|
//#region ../../default/po-codemode/src/extensions/workspaces/sessions/(backend)/resource/codemode-how-to-llm.server.ts
|
|
2615
2714
|
var codemode_how_to_llm_server_default = defineResource({
|
|
2616
2715
|
name: "codemode-how-to-llm",
|
|
@@ -2665,6 +2764,8 @@ var exec_server_default = defineServerTool((context) => context.root.exec);
|
|
|
2665
2764
|
//#endregion
|
|
2666
2765
|
//#region ../../default/po-codemode/generated/server.ts
|
|
2667
2766
|
const at = (value, context) => typeof value === "function" ? value(context) : value;
|
|
2767
|
+
/* v8 ignore next -- generated normalization branch */
|
|
2768
|
+
const defined = (values) => values.filter((value) => value !== void 0);
|
|
2668
2769
|
const via = (identity, value) => value === void 0 ? void 0 : {
|
|
2669
2770
|
...identity,
|
|
2670
2771
|
...value
|
|
@@ -2674,6 +2775,12 @@ const serverPlugin = defineServerPlugin({
|
|
|
2674
2775
|
providerOverrides: composeServerProviderOverrides(root_server_default),
|
|
2675
2776
|
provides: { session: [codemode_server_default] },
|
|
2676
2777
|
injects: composeRootInjects({ session: [root_server_default] }),
|
|
2778
|
+
host: (context) => ({ get channels() {
|
|
2779
|
+
return [() => via({ frameType: "codemode_background" }, at(codemodeBackground_server_default, context))];
|
|
2780
|
+
} }),
|
|
2781
|
+
workspace: (context) => ({ get channels() {
|
|
2782
|
+
return defined([context.hosted("host") ? void 0 : () => via({ frameType: "codemode_background" }, at(codemodeBackground_server_default, context))]);
|
|
2783
|
+
} }),
|
|
2677
2784
|
session: async (context) => {
|
|
2678
2785
|
const scopeSession = await context.scopeRoot("session", root_server_default, context);
|
|
2679
2786
|
const contextSession = {
|
|
@@ -2682,6 +2789,12 @@ const serverPlugin = defineServerPlugin({
|
|
|
2682
2789
|
};
|
|
2683
2790
|
return {
|
|
2684
2791
|
...composeRootHooks(scopeSession),
|
|
2792
|
+
get channels() {
|
|
2793
|
+
return defined([context.hosted("host") ? void 0 : () => via({ frameType: "codemode_background" }, at(codemodeBackground_server_default, context))]);
|
|
2794
|
+
},
|
|
2795
|
+
get commands() {
|
|
2796
|
+
return [via({ name: "background-scripts-stop" }, at(background_scripts_stop_server_default, contextSession))];
|
|
2797
|
+
},
|
|
2685
2798
|
get resources() {
|
|
2686
2799
|
return [
|
|
2687
2800
|
at(codemode_how_to_llm_server_default, contextSession),
|