@theoremjs/studio 0.3.4-next.855.gc82d4ec → 0.3.4-next.863.gb601f58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -5
  3. package/page/assets/Badge-C0KjAK5l.js +1 -0
  4. package/page/assets/BaseTypeahead-BM3FoulY.js +1 -0
  5. package/page/assets/BottomSheet-B8-prREc.js +1 -0
  6. package/page/assets/Button-Cb-mh6ml.js +1 -0
  7. package/page/assets/{Card-DKuxiCN0.js → Card-BUIbjVIe.js} +1 -1
  8. package/page/assets/{Center-C9ai7fq_.js → Center-BVnAO8rr.js} +1 -1
  9. package/page/assets/{CheckboxIndicator-Cca43Ctu.js → CheckboxIndicator-CWc5B_d1.js} +2 -2
  10. package/page/assets/CheckboxInput-BrhD5W3u.js +2 -0
  11. package/page/assets/CodeBlock-B8SfIXyW.js +3 -0
  12. package/page/assets/{CollapsibleGroup-D_hnA9UR.js → CollapsibleGroup-BnWI_jMR.js} +1 -1
  13. package/page/assets/ConsoleFrame-CYYtfWNI.js +3 -0
  14. package/page/assets/DateInput-CaOcecG2.js +1 -0
  15. package/page/assets/Dialog-BatAn-DX.js +1 -0
  16. package/page/assets/EmptyState-B_rMeBCn.js +1 -0
  17. package/page/assets/Field-BSCYng6A.js +1 -0
  18. package/page/assets/FieldStatus-D_97agai.js +1 -0
  19. package/page/assets/{HStack-CqE4exX9.js → HStack-D3i0gAme.js} +1 -1
  20. package/page/assets/HoverCard-YEWLJPhx.js +1 -0
  21. package/page/assets/Icon-C9dlIB4I.js +48 -0
  22. package/page/assets/{IconButton-Jbcy-K-d.js → IconButton-Crxt9XEq.js} +1 -1
  23. package/page/assets/{ItemSwipeLayer-Vrel9VQX.js → ItemSwipeLayer-CVeHWmee.js} +1 -1
  24. package/page/assets/LayoutContent-NlcSjVn7.js +1 -0
  25. package/page/assets/ListItem-C80mhugw.js +1 -0
  26. package/page/assets/{MenuBottomSheet-BCqfbf6e.js → MenuBottomSheet-Ctymn_LQ.js} +1 -1
  27. package/page/assets/{MenuBottomSheetActionList-4BzDY0Sv.js → MenuBottomSheetActionList-BkRKLMkR.js} +1 -1
  28. package/page/assets/OverflowList-T3oyz0uY.js +1 -0
  29. package/page/assets/PanelSearchInput-CGk0XlVX.js +1 -0
  30. package/page/assets/SchemaFields-D1_c3uax.js +1 -0
  31. package/page/assets/ScrollableArea-Db8BBKVt.js +1 -0
  32. package/page/assets/SegmentedControlItem-CTVJbfcv.js +1 -0
  33. package/page/assets/SidePanel-7cMNIHsg.js +2 -0
  34. package/page/assets/Spinner-sCbvL2qs.js +1 -0
  35. package/page/assets/{Stack-De5MY0tq.js → Stack-BZiu21ta.js} +1 -1
  36. package/page/assets/Text-DfN1tSUL.js +2 -0
  37. package/page/assets/TextInput-CYSGEp-G.js +1 -0
  38. package/page/assets/{TimestampHoverCard-Lt3iYlao.js → TimestampHoverCard-0-rfsRpo.js} +1 -1
  39. package/page/assets/Token-C0MCeuZZ.js +1 -0
  40. package/page/assets/TokenizerBottomSheet-BOahsgu5.js +1 -0
  41. package/page/assets/{ToolResultCharts-DR8osutJ.js → ToolResultCharts-DxlRxTlp.js} +1 -1
  42. package/page/assets/{Toolbar-BKXtT7K9.js → Toolbar-DzqcK9Za.js} +1 -1
  43. package/page/assets/Tooltip-BO0yrDVt.js +1 -0
  44. package/page/assets/TraceInspector-BR3SDDuV.js +1 -0
  45. package/page/assets/{TraceOverview--MUkT_lP.js → TraceOverview-bvtLAnsR.js} +2 -2
  46. package/page/assets/{VStack-CCYGIv4A.js → VStack-BGVV0uKl.js} +1 -1
  47. package/page/assets/{browser-engine-DLkf7rll.js → browser-engine-DctWhKjF.js} +3 -3
  48. package/page/assets/{browser-transport-_E7cXrRm.js → browser-transport-DVnbvtNO.js} +2 -2
  49. package/page/assets/browserClickWait-F6QvgsDI.js +1 -0
  50. package/page/assets/{layerScopedContext-BA4VBuWG.js → devWarning-B-QAZEJI.js} +1 -1
  51. package/page/assets/{embedding-space-view-CRxJE7jA.js → embedding-space-view-D-Bnd0fH.js} +1 -1
  52. package/page/assets/{export-agent-TUBILmVw.js → export-agent-DbT9mJEv.js} +3 -3
  53. package/page/assets/fieldParts-DJZ7Rxcc.js +1 -0
  54. package/page/assets/{focusReturn-DF3Bi_HC.js → focusReturn-C7gRi2IE.js} +1 -1
  55. package/page/assets/{guardrail-tester-C2ahl2Sm.js → guardrail-tester-XhX2mqHc.js} +2 -2
  56. package/page/assets/highlightStyles-C7fXGwpK.js +50 -0
  57. package/page/assets/index-C1WNmgOO.js +150 -0
  58. package/page/assets/inputStyles.stylex-CwhFgCYO.js +1 -0
  59. package/page/assets/isApplePlatform-BSwFAKoe.js +1 -0
  60. package/page/assets/json-code-DoIDKNEG.js +3 -0
  61. package/page/assets/{labels-provider-W8DCgjbB.js → labels-provider-Bv9WPagB.js} +1 -1
  62. package/page/assets/{map-token-_aDyWhNO.js → map-token-CgKWabfH.js} +1 -1
  63. package/page/assets/menuBottomSheet.stylex-DRbZhkuJ.js +1 -0
  64. package/page/assets/prompt-row-Bsz-A4Bf.js +75 -0
  65. package/page/assets/{read-map-i9VRmt7r.js → read-map-BJqwz_gJ.js} +1 -1
  66. package/page/assets/sharedMutationObserver-BHa8gqlp.js +1 -0
  67. package/page/assets/{studio-code-pane-Krc6R7c4.js → studio-code-pane-Db-AAr3b.js} +2 -2
  68. package/page/assets/{studio-console-Cdmx1jE7.js → studio-console-71u2GwPw.js} +1 -1
  69. package/page/assets/{studio-decision-SUjLe9LY.js → studio-decision-BHPpdQM9.js} +1 -1
  70. package/page/assets/studio-embedding-VyWNTUU8.js +2 -0
  71. package/page/assets/studio-host-console-C1Rt8PSv.js +2 -0
  72. package/page/assets/studio-labels-EQRWPOr5.js +3 -0
  73. package/page/assets/{studio-live-DVVhjsUt.js → studio-live-D0pjddZ9.js} +3 -3
  74. package/page/assets/{studio-map-DXfBjKcg.js → studio-map-CpYHfNRm.js} +1 -1
  75. package/page/assets/studio-trace-replay-B0O6qFwD.js +3 -0
  76. package/page/assets/{InputClearButton-ClwCL3dr.js → textEntryTraits-C8qoTZ3W.js} +1 -1
  77. package/page/assets/{trace-patterns-DFMwRU00.js → trace-patterns-YZSpKAfw.js} +1 -1
  78. package/page/assets/{use-one-call-Cp4nCdQC.js → use-one-call-CMoYqsKk.js} +1 -1
  79. package/page/assets/use-second-ticker-C09v74b0.css +1 -0
  80. package/page/assets/useAnnounceRenderedText-BWNmfFlE.js +1 -0
  81. package/page/assets/useBusyAnnouncement-DwJYqyJC.js +1 -0
  82. package/page/assets/useClipboard-C7IeReFJ.js +1 -0
  83. package/page/assets/useFocusLeavingChange-8rK2N7Tp.js +1 -0
  84. package/page/assets/useHighlightedOptionScroll-Do3FP80C.js +1 -0
  85. package/page/assets/useIsHydrating-wiKgLSH8.js +1 -0
  86. package/page/assets/useKeyboardHint-B6oH_Cll.js +1 -0
  87. package/page/assets/useLayerDismissal-CqRa7y6J.js +1 -0
  88. package/page/assets/useLocale-DtI8SMic.js +1 -0
  89. package/page/assets/useMediaQuery-Dvkq1PZg.js +1 -0
  90. package/page/assets/useMenuOverflow-x8Ox3IyG.js +1 -0
  91. package/page/assets/useMenuPress-DM12OZUv.js +1 -0
  92. package/page/assets/useMergedRefs-DJD-JnFZ.js +1 -0
  93. package/page/assets/usePressFeedback-nkH67NDc.js +1 -0
  94. package/page/assets/useResolvedRequired-B-0WnbIo.js +1 -0
  95. package/page/assets/useScrollLock--U5R1vFj.js +1 -0
  96. package/page/assets/useScrollableArea-uSlz-RoI.js +1 -0
  97. package/page/assets/{useSettledOpen-DTsZ7A6A.js → useSettledOpen-BJQ5dTsM.js} +1 -1
  98. package/page/assets/useTooltip-NPYEayzZ.js +1 -0
  99. package/page/assets/{useTranslator-Ba7ULSHc.js → useTranslator-CGZ-h6ng.js} +1 -1
  100. package/page/index.html +70 -70
  101. package/ui/built/theme.css +2 -2
  102. package/ui/built/theme.css.d.ts +2 -2
  103. package/ui/built/theorem-studio.d.ts +2 -2
  104. package/ui/built/theorem-studio.js +3 -3
  105. package/ui/built/theorem-studio.variants.d.ts +2 -2
  106. package/page/assets/Badge-Cj3D81QB.js +0 -1
  107. package/page/assets/BottomSheet-DpTM44kf.js +0 -1
  108. package/page/assets/Button-98PahHB4.js +0 -1
  109. package/page/assets/CheckboxInput-nEEHX5M1.js +0 -2
  110. package/page/assets/CodeBlock-D7u2qG-t.js +0 -3
  111. package/page/assets/ConsoleFrame-DIxyRKED.js +0 -3
  112. package/page/assets/DateInput-C4wSabnj.js +0 -1
  113. package/page/assets/Dialog-C2GP5P7V.js +0 -1
  114. package/page/assets/EmptyState-DVoDGbtj.js +0 -1
  115. package/page/assets/FieldStatus-mbnJ60bK.js +0 -1
  116. package/page/assets/HoverCard-BaUeXNdO.js +0 -1
  117. package/page/assets/Icon-Cluq4EiW.js +0 -48
  118. package/page/assets/LayoutContent-ClBE78rU.js +0 -1
  119. package/page/assets/LayoutFooter-QMRRAZfF.js +0 -1
  120. package/page/assets/ListItem-BevY6nJP.js +0 -1
  121. package/page/assets/OverflowList-CDkPnQmt.js +0 -1
  122. package/page/assets/PanelSearchInput-Dw5TVlEX.js +0 -1
  123. package/page/assets/SchemaFields-DcqZAqsD.js +0 -1
  124. package/page/assets/ScrollableArea-BGmyGfiL.js +0 -1
  125. package/page/assets/SidePanel-CYk_zksv.js +0 -2
  126. package/page/assets/Spinner-B6MdidYQ.js +0 -1
  127. package/page/assets/Text-BDwNaqzZ.js +0 -2
  128. package/page/assets/TextInput-BRBEgg_h.js +0 -1
  129. package/page/assets/Token-BZrQH6-I.js +0 -1
  130. package/page/assets/TokenizerBottomSheet-D9-Y84hI.js +0 -1
  131. package/page/assets/Tooltip-Dhy5lIDA.js +0 -1
  132. package/page/assets/TraceInspector-CTf5pXLc.js +0 -1
  133. package/page/assets/devWarning-DxuplmRl.js +0 -1
  134. package/page/assets/fieldParts-DOfguMAs.js +0 -1
  135. package/page/assets/highlightRanges-B7TRPq9q.js +0 -51
  136. package/page/assets/index-DNFrrd7f.js +0 -150
  137. package/page/assets/inputStyles.stylex-Dmh4r-B9.js +0 -1
  138. package/page/assets/isRenderable-DHkzpAoQ.js +0 -1
  139. package/page/assets/json-code-6CMWxg9k.js +0 -3
  140. package/page/assets/menuBottomSheet.stylex-BoKs4EdV.js +0 -1
  141. package/page/assets/padding.stylex-BWRTzhFl.js +0 -1
  142. package/page/assets/prompt-row-Dfq6zt8n.js +0 -71
  143. package/page/assets/studio-embedding-CUtJxKkB.js +0 -2
  144. package/page/assets/studio-host-console-C5kM-YLK.js +0 -2
  145. package/page/assets/studio-labels-CUaktj1R.js +0 -3
  146. package/page/assets/studio-trace-replay-3BPGonrL.js +0 -3
  147. package/page/assets/use-second-ticker-D0uA9-ps.css +0 -1
  148. package/page/assets/useAnnounce-QM3mmuiE.js +0 -1
  149. package/page/assets/useAnnounceRenderedText-_-FYc-5m.js +0 -1
  150. package/page/assets/useBusyAnnouncement-CjJI13FX.js +0 -1
  151. package/page/assets/useClipboard-CAtohmvr.js +0 -1
  152. package/page/assets/useDevWarning-WeXt8Pe8.js +0 -1
  153. package/page/assets/useFocusLeavingChange-Bb1WH0Lr.js +0 -1
  154. package/page/assets/useHighlightedOptionScroll-CFs91KPl.js +0 -1
  155. package/page/assets/useIsHydrating-JHu3d-Y0.js +0 -1
  156. package/page/assets/useKeyboardHint-BP66YM6d.js +0 -1
  157. package/page/assets/useLayerDismissal-7g2rAKDN.js +0 -1
  158. package/page/assets/useLocale-d7ARRGFj.js +0 -1
  159. package/page/assets/useMediaQuery-D0tQ79Tl.js +0 -1
  160. package/page/assets/useMenuOverflow-nA_EuFZP.js +0 -1
  161. package/page/assets/useMenuPress-BHmqa9bx.js +0 -1
  162. package/page/assets/useMergedRefs-BgzyWuff.js +0 -1
  163. package/page/assets/usePressFeedback-BpX4yZ5R.js +0 -1
  164. package/page/assets/useResolvedRequired-DR7Agwbm.js +0 -1
  165. package/page/assets/useScrollLock-Dm92sJDr.js +0 -1
  166. package/page/assets/useScrollableArea-CIrHdx_f.js +0 -1
  167. package/page/assets/useTooltip-ClCeZiOV.js +0 -1
  168. /package/page/assets/{use-second-ticker-ovc65-Bo.js → use-second-ticker-CDQ3LLWp.js} +0 -0
@@ -1,5 +1,5 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-ClBE78rU.js";import{t as a}from"./StackItem-ClAjT294.js";import{t as o}from"./Icon-Cluq4EiW.js";import{a as s,c,l,p as u,u as d}from"./SidePanel-CYk_zksv.js";import{t as f}from"./Text-BDwNaqzZ.js";import{t as p}from"./Button-98PahHB4.js";import{b as m,g as h,p as g,s as _,t as v}from"./browser-transport-_E7cXrRm.js";import{t as y}from"./createReactComponent-DVEyVJ-p.js";import{t as b}from"./Center-C9ai7fq_.js";import{_ as x,g as S,h as C,m as w,n as T,r as E,t as ee}from"./studio-labels-CUaktj1R.js";import{t as te}from"./IconMicrophone-BT77cilC.js";import{c as D}from"./host-patterns-F-KZIzkF.js";import{Or as O,Ur as k,or as A,sr as j}from"./shaped-data-CtJtZSw9.js";import{S as M,g as N,r as P,t as F}from"./reader-DhyhAoss.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as ne,y as re}from"./turn-client-CobwqNwm.js";import{r as ie,t as ae}from"./live-messages-iGBTap-t.js";import{t as oe}from"./EmptyState-DVoDGbtj.js";import"./use-second-ticker-ovc65-Bo.js";import{a as se,n as L,t as R}from"./labels-provider-W8DCgjbB.js";import{t as z}from"./HStack-CqE4exX9.js";import{t as B}from"./IconButton-Jbcy-K-d.js";import{t as V}from"./VStack-CCYGIv4A.js";import{t as ce}from"./Toolbar-BKXtT7K9.js";import{t as le}from"./Dialog-C2GP5P7V.js";import{Bt as ue,D as H,H as U,Ht as de,L as fe,M as W,N as pe,Nt as me,Vt as he,Zt as ge,_t as _e,ct as ve,l as ye,w as be,y as xe}from"./index-DNFrrd7f.js";var Se=y(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),Ce=y(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),we=y(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Te=y(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),G=y(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ee=y(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),De=y(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),K=y(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Oe(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function ke(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Ae(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function je(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var q=new Set;async function Me(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!q.has(n)&&(q.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Ne(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Pe=`mic-capture-processor`;function Fe(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Ie(e,t,n=16e3){if(t===n)return Le(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=Re(i>0?n/i:0),o++,s=t}return a}function Le(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=Re(e[n]??0);return t}function Re(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new D(`internal`,O(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=ue(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return ke({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new D(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new D(`network`,`live call dropped and could not reconnect`)),this.lostAt=e}else this.reconnectTries+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.open(`reconnecting`)},e)}failOpen(e){this.status===`reconnecting`?(this.teardownConnection(),this.scheduleReconnect()):this.startOver()||this.failSession(e)}async open(e){this.teardownConnection(),this.sessionOver=!1,this.setStatus(e),e===`connecting`&&this.setConnectPhase(`socket`);try{let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume();let t=globalThis.location.protocol===`https:`?`wss:`:`ws:`,n=this.options.profile?`?profile=${encodeURIComponent(this.options.profile)}`:``,r=`${t}//${globalThis.location.host}/api/live/relay${n}`,i=this.options.relayUrl||r;this.ws=this.createSocket(i),this.ws.binaryType=`arraybuffer`,this.ws.onopen=()=>{let e=this.openMessage();this.sentContext=JSON.stringify(e.context),this.ws?.send(JSON.stringify(e))},this.connectTimeout=setTimeout(()=>{this.opening&&this.failOpen(new D(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new D(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new D(`network`,`live socket error`))}}catch(e){this.failOpen(new D(`internal`,O(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Ne(e);this.failSession(new D(t?`auth`:`internal`,O(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Ie(e,t,16e3),r=j(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(he(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Fe()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Pe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(de(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Me({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:ne(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=ie(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(e.body,`request`)):e.status===`dispatched`?t.resolve({status:`dispatched`,grantId:e.grantId,arguments:e.arguments}):e.status===`gated`?t.resolve({status:`gated`,gate:e.gate}):t.resolve({status:`settled`}))}async tryHandleControlEnvelope(e){return e.type===`ready`?(await this.handleReadyEnvelope(e),!0):e.type===`executeToolResult`?(this.handleExecuteToolResultEnvelope(e),!0):e.type===`trace`?(this.options.onTrace?.(e.record),!0):e.type===`error`&&(this.startOver()||(this.sessionOver=!0,this.options.onError?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:je(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Ae(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new D(`request`,`live session is not connected`);let n=ae.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new D(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new D(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Je(e,t){return t.length===0?e:[...e,[...t]]}function Ye(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?re(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&ot(t.text,e.text))})}function ct(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-NlcSjVn7.js";import{t as a}from"./StackItem-ClAjT294.js";import{t as o}from"./Icon-C9dlIB4I.js";import{a as s,c,l,p as u,u as d}from"./SidePanel-7cMNIHsg.js";import{t as f}from"./Text-DfN1tSUL.js";import{t as p}from"./Button-Cb-mh6ml.js";import{b as m,g as h,p as g,s as _,t as v}from"./browser-transport-DVnbvtNO.js";import{t as y}from"./createReactComponent-DVEyVJ-p.js";import{t as b}from"./Center-BVnAO8rr.js";import{_ as x,g as S,h as C,m as w,n as T,r as E,t as ee}from"./studio-labels-EQRWPOr5.js";import{t as te}from"./IconMicrophone-BT77cilC.js";import{c as D}from"./host-patterns-F-KZIzkF.js";import{Or as O,Ur as k,or as A,sr as j}from"./shaped-data-CtJtZSw9.js";import{S as M,g as N,r as P,t as F}from"./reader-DhyhAoss.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as ne,y as re}from"./turn-client-CobwqNwm.js";import{r as ie,t as ae}from"./live-messages-iGBTap-t.js";import{t as oe}from"./EmptyState-B_rMeBCn.js";import"./use-second-ticker-CDQ3LLWp.js";import{a as se,n as L,t as R}from"./labels-provider-Bv9WPagB.js";import{t as z}from"./HStack-D3i0gAme.js";import{t as B}from"./IconButton-Crxt9XEq.js";import{t as V}from"./VStack-BGVV0uKl.js";import{t as ce}from"./Toolbar-DzqcK9Za.js";import{t as le}from"./Dialog-BatAn-DX.js";import{A as ue,B as H,Bt as de,F as fe,Jt as pe,Rt as me,c as he,ht as ge,jt as _e,k as U,ot as ve,v as ye,w as W,x as be,zt as xe}from"./index-C1WNmgOO.js";var Se=y(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),Ce=y(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),we=y(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Te=y(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),G=y(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ee=y(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),De=y(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),K=y(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Oe(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function ke(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Ae(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function je(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var q=new Set;async function Me(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!q.has(n)&&(q.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Ne(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Pe=`mic-capture-processor`;function Fe(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Ie(e,t,n=16e3){if(t===n)return Le(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=Re(i>0?n/i:0),o++,s=t}return a}function Le(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=Re(e[n]??0);return t}function Re(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new D(`internal`,O(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=me(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return ke({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new D(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new D(`network`,`live call dropped and could not reconnect`)),this.lostAt=e}else this.reconnectTries+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.open(`reconnecting`)},e)}failOpen(e){this.status===`reconnecting`?(this.teardownConnection(),this.scheduleReconnect()):this.startOver()||this.failSession(e)}async open(e){this.teardownConnection(),this.sessionOver=!1,this.setStatus(e),e===`connecting`&&this.setConnectPhase(`socket`);try{let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume();let t=globalThis.location.protocol===`https:`?`wss:`:`ws:`,n=this.options.profile?`?profile=${encodeURIComponent(this.options.profile)}`:``,r=`${t}//${globalThis.location.host}/api/live/relay${n}`,i=this.options.relayUrl||r;this.ws=this.createSocket(i),this.ws.binaryType=`arraybuffer`,this.ws.onopen=()=>{let e=this.openMessage();this.sentContext=JSON.stringify(e.context),this.ws?.send(JSON.stringify(e))},this.connectTimeout=setTimeout(()=>{this.opening&&this.failOpen(new D(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new D(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new D(`network`,`live socket error`))}}catch(e){this.failOpen(new D(`internal`,O(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Ne(e);this.failSession(new D(t?`auth`:`internal`,O(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Ie(e,t,16e3),r=j(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(xe(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Fe()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Pe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(de(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Me({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:ne(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=ie(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(e.body,`request`)):e.status===`dispatched`?t.resolve({status:`dispatched`,grantId:e.grantId,arguments:e.arguments}):e.status===`gated`?t.resolve({status:`gated`,gate:e.gate}):t.resolve({status:`settled`}))}async tryHandleControlEnvelope(e){return e.type===`ready`?(await this.handleReadyEnvelope(e),!0):e.type===`executeToolResult`?(this.handleExecuteToolResultEnvelope(e),!0):e.type===`trace`?(this.options.onTrace?.(e.record),!0):e.type===`error`&&(this.startOver()||(this.sessionOver=!0,this.options.onError?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:je(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Ae(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new D(`request`,`live session is not connected`);let n=ae.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new D(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new D(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Je(e,t){return t.length===0?e:[...e,[...t]]}function Ye(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?re(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&ot(t.text,e.text))})}function ct(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
2
2
  `),r=e?.join(`
3
- `);(0,Z.useEffect)(()=>{r!==void 0&&me(r?r.split(`
3
+ `);(0,Z.useEffect)(()=>{r!==void 0&&_e(r?r.split(`
4
4
  `):[],n?n.split(`
5
- `):[])},[r,n])}var ft=.62,pt=400;function mt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function ht(e,t){let n=t?.facingMode??`user`;return mt(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new D(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,ft).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,pt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await mt(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function gt(e){let t=(0,Z.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,Z.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,Z.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>Qe(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Z.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await ht(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,Z.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,Z.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,Z.useCallback)(async()=>{t(),await n()},[n,t])}}function _t(e,t){return t.activity===void 0&&e?.name===t.name?e:t}function vt(e){return new N(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function yt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Q(t):e.phase===`error`?(t.reportFailure(vt(e.failure)),Q(t)):t.setActiveTool(e.phase===`running`&&e.activity?{name:e.name,activity:e.activity}:{name:e.name})}function bt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&yt(e.tool,t)}function xt(e){let[t,n]=(0,Z.useState)(`disconnected`),[r,i]=(0,Z.useState)(null),a=(0,Z.useRef)({input:0,output:0}),o=(0,Z.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Z.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(qe),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)([]),[ee,te]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(`user`),j=(0,Z.useRef)(null),M=(0,Z.useRef)(h),N=(0,Z.useRef)(c),P=(0,Z.useRef)(T),F=(0,Z.useRef)(t);return M.current=h,N.current=c,P.current=T,F.current=t,(0,Z.useEffect)(()=>{C&&te(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:f,setActiveTool:p,captions:h,setCaptions:g,failure:_,reportFailure:(0,Z.useCallback)(t=>{v(m(t,e))},[e]),clearFailure:(0,Z.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Z.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Z.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:E,everConnected:ee,videoPreview:D,setVideoPreview:O,videoFacingMode:k,setVideoFacingMode:A,videoCaptureRef:j,captionsRef:M,isMutedRef:N,sessionPermissionsRef:P,statusRef:F,resetCaptions:(0,Z.useCallback)(()=>{g(qe())},[]),stopVideo:(0,Z.useCallback)(()=>{j.current&&=(j.current.stop(),null),O(null),A(`user`),d(!1)},[])}}function St(e){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Z.useCallback)(t=>{e.setCaptions(e=>nt(e,t)),bt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>ut(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:t=>{e.setActiveTool(e=>_t(e,t))}})},[e,o]),waitForGateDecision:(0,Z.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Z.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Z.useCallback)(()=>{a.current?.(new D(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function Ct(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function wt(e,t,n,r){r.setCaptions(r=>Qe(r,e,t,n?.interim))}async function Tt(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=x({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Et(e){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Z.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Ke({...e,options:r.options,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{Ct(e,n.current)},onTranscript:(e,t,r)=>{wt(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>Tt(e,n.current)});return t.current=i,i},[]),clearClient:(0,Z.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Dt(e,t,n,r){let[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(!1),d=(0,Z.useCallback)(t=>{u.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Z.useEffect)(()=>{n&&l(e=>e??Date.now())},[n]),(0,Z.useEffect)(()=>{n&&u.current&&(u.current=!1,e.handleToggleVideo())},[e,n]);let f=(0,Z.useCallback)(()=>{u.current=!1,e.teardownSession(),s(!0),l(null)},[e]),[p,m]=(0,Z.useState)([]),h=(0,Z.useCallback)(async()=>{let n=t.current.turns;m(e=>Je(e,n)),s(!1),l(null),await e.handleRestart()},[e,t]),g=(0,Z.useRef)(e.teardownSession);return g.current=e.teardownSession,(0,Z.useEffect)(()=>()=>{g.current()},[]),{callStarted:i,connectedAt:c,ended:o,pastCalls:p,startCall:d,handleEnd:f,handleRestart:h}}function Ot({iface:e,connection:t,...n}){let r=xt(e.labels),i=St({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Z.useRef)(t);a.current=t;let o=I(e.live.ingress,`audio`),s=I(e.live.ingress,`video`),c=I(e.live.ingress,`text`),l=(0,Z.useMemo)(()=>Oe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool?.name??null,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Z.useMemo)(h,[]),{clientRef:d,ensureClient:f,clearClient:p}=Et({options:n.options,stated:n.stated,model:n.model,effort:n.effort,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),m=gt({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,connectedAt:_,ended:v,pastCalls:y,startCall:b,handleEnd:x,handleRestart:S}=Dt(m,r.captionsRef,r.sessionActive,s),C=JSON.stringify(n.context);(0,Z.useEffect)(()=>{d.current?.setContext(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.options);(0,Z.useEffect)(()=>{d.current?.setOptions(w===void 0?void 0:JSON.parse(w))},[d,w]);let T=JSON.stringify(n.stated);return(0,Z.useEffect)(()=>{d.current?.setStated(T===void 0?void 0:JSON.parse(T))},[d,T]),dt(e.tools.page,n.pageTools),{iface:e,handle:e.identity.handle,traces:u,callStarted:g,connectedAt:_,pastCalls:y,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||v||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:x,startCall:b,handleRestart:S,handleSendText:m.handleSendText,handleToggleMic:m.handleToggleMic,handleFlipCamera:m.handleFlipCamera,handleToggleVideo:m.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=n();function kt(e){return(0,$.jsx)(R,{children:(0,$.jsx)(At,{...e})})}function At({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l,showComposer:u=!0,leading:d}){let f=L(),p=f(`@theorem.agent.handle`,{handle:e}),{blocks:m,callStarts:h}=ct(n,t),g=f(`@theorem.live.new_session`),_=Object.fromEntries(h.map(e=>[e,g])),v=u?(0,$.jsx)(ve,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l}):null;return(0,$.jsxs)(V,{height:`100%`,children:[d,(0,$.jsx)(a,{size:`fill`,children:m.length>0?(0,$.jsx)(s,{label:f(`@theorem.panel.captions.name`),children:(0,$.jsx)(fe,{blocks:m,dividers:_,handle:p,streaming:lt(t)})}):(0,$.jsx)(V,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(oe,{icon:(0,$.jsx)(o,{icon:Ee,size:`lg`,color:`secondary`}),title:f(`@theorem.panel.captions.empty.title`),description:f(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),v]})}var jt=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new D(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await v(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new D(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new D(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal,execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,background:t.background??a?.background},{vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...P(t,e.profile.labels,F)}),this.close()}}async attach(e,t,n,r,i,a={}){let o=e({send:e=>{typeof e==`string`&&this.receive(JSON.parse(e))},close:()=>this.close(),addEventListener:this.outbound.addEventListener.bind(this.outbound)},t,n,crypto.randomUUID(),r,i,{...a,clientEvents:F});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function Mt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new jt(e,t,r)}}var Nt={borderRadius:`var(--radius-chat, var(--radius-container))`};function Pt({call:e}){let t=L(),n=e.gatePrompt,r=e.resolveGateDecision,i=t(`@theorem.agent.handle`,{handle:e.handle});return(0,$.jsx)(le,{isOpen:n!==null,purpose:`required`,width:400,padding:0,style:Nt,onOpenChange:e=>{e||r({action:`deny`})},children:n?n.gate.kind===`auth`?(0,$.jsx)(E,{gate:n.gate,toolName:n.gate.tool,onAuthenticated:e=>{r({action:`auth`,secret:e})}}):(0,$.jsx)(T,{gate:n.gate,toolName:n.gate.tool,agent:i,input:n.input,onDecision:e=>{r({action:e})}}):null})}function Ft({video:e,facingMode:t}){let n=L(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,Z.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(w,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var It=720,Lt=320;function Rt({theme:e,mode:t,labels:n,...r}){return(0,$.jsx)(_,{theme:e,mode:t,children:(0,$.jsx)(R,{labels:n,children:(0,$.jsx)(zt,{...r})})})}function zt({call:e,trace:t,onMinimize:n}){let a=L(),s=(0,Z.useRef)(null),f=pe(e.iface,e.traces,t),p=u(s,!0),m={name:a(`@theorem.panel.captions.name`),show:a(`@theorem.panel.captions.show`),hide:a(`@theorem.panel.captions.hide`),resize:a(`@theorem.panel.captions.resize`)},h=(0,$.jsx)(d,{labels:m,icon:(0,$.jsx)(o,{icon:ge}),panelId:p.id,open:p.open,onToggle:p.toggle});return e.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(c,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,$.jsx)(Kt,{call:e})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(V,{height:`100%`,padding:3,children:(0,$.jsx)(Vt,{call:e,captionsToggle:h,onMinimize:n})})})})})})}),(0,$.jsx)(Pt,{call:e})]}):(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Bt,{call:e})})})})}function Bt({call:e}){let t=L();return(0,$.jsx)(V,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(b,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:be,gap:8,children:[(0,$.jsxs)(V,{gap:1,children:[(0,$.jsx)(f,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(z,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(p,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(p,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(o,{icon:K}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Vt({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=Ht();return(0,$.jsx)(V,{ref:i,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:It,height:`100%`,gap:3,children:[(0,$.jsxs)(V,{gap:.5,children:[(0,$.jsx)(f,{type:`label`,color:`secondary`,children:r(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{size:`sm`,color:`secondary`,children:se(r,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(H,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(H,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(a,{size:`fill`,children:(0,$.jsx)(V,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(V,{width:`100%`,height:Lt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(_e,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Ut,{call:e,captionsToggle:t,onMinimize:n})]})})}function Ht(){let e=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Ut({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=!e.sessionActive,a=[];return e.voiceAvailable&&a.push((0,$.jsx)(U,{label:r(`@theorem.live.microphone`),tooltip:r(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:i,icon:(0,$.jsx)(o,{icon:te}),pressedIcon:(0,$.jsx)(o,{icon:we}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&a.push((0,$.jsx)(Wt,{call:e},`video`)),n&&a.push((0,$.jsx)(B,{label:r(`@theorem.live.minimize`),tooltip:r(`@theorem.live.minimize`),variant:`ghost`,icon:(0,$.jsx)(o,{icon:Se}),onClick:n},`minimize`)),a.push((0,$.jsx)(Z.Fragment,{children:t},`captions`),(0,$.jsx)(Gt,{call:e},`call`)),(0,$.jsx)(ce,{label:r(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(z,{gap:2,vAlign:`center`,children:a})})}function Wt({call:e}){let t=L(),n=!e.sessionActive;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(U,{label:t(`@theorem.live.camera`),tooltip:t(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:n,icon:(0,$.jsx)(o,{icon:K}),pressedIcon:(0,$.jsx)(o,{icon:De}),onPressedChange:()=>{e.handleToggleVideo()}}),e.isVideoOn?(0,$.jsx)(B,{label:t(`@theorem.live.flip_camera`),tooltip:t(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:n,icon:(0,$.jsx)(o,{icon:Ce}),onClick:()=>{e.handleFlipCamera()}}):null]})}function Gt({call:e}){let t=L();return e.canRestart?(0,$.jsx)(B,{label:t(`@theorem.live.start_call`),tooltip:t(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>{e.handleRestart()}}):(0,$.jsx)(B,{label:t(`@theorem.live.end_call`),tooltip:t(`@theorem.live.end_call`),variant:`destructive`,isDisabled:!e.sessionActive,icon:(0,$.jsx)(o,{icon:Te}),onClick:e.handleEnd})}function Kt({call:e}){return(0,$.jsx)(kt,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,$.jsx)(Ft,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function qt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(Yt,{...t,connect:()=>e?Mt(n,e):C(n)})}function Jt({endpoint:e,...t}){let{actingAs:n}=ye();return(0,$.jsx)(Yt,{...t,connect:()=>({createSocket:()=>new WebSocket(xe(e,n))})})}function Yt({payload:e,note:t,connect:n,trace:r,options:i,stated:a,context:o}){let s=(0,Z.useMemo)(()=>g(e),[e]),c=(0,Z.useMemo)(()=>S(e),[e]);return s.type===`live`?(0,$.jsx)(Xt,{iface:s,connection:()=>(t(),n()),trace:r,options:i,stated:a,context:o,pageTools:c}):null}function Xt({trace:e,...t}){let n=Ot(t);return(0,$.jsx)(Rt,{labels:ee,call:n,trace:e})}export{Jt as ProjectLive,qt as StudioLive};
5
+ `):[])},[r,n])}var ft=.62,pt=400;function mt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function ht(e,t){let n=t?.facingMode??`user`;return mt(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new D(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,ft).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,pt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await mt(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function gt(e){let t=(0,Z.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,Z.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,Z.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>Qe(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Z.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await ht(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,Z.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,Z.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,Z.useCallback)(async()=>{t(),await n()},[n,t])}}function _t(e,t){return t.activity===void 0&&e?.name===t.name?e:t}function vt(e){return new N(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function yt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Q(t):e.phase===`error`?(t.reportFailure(vt(e.failure)),Q(t)):t.setActiveTool(e.phase===`running`&&e.activity?{name:e.name,activity:e.activity}:{name:e.name})}function bt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&yt(e.tool,t)}function xt(e){let[t,n]=(0,Z.useState)(`disconnected`),[r,i]=(0,Z.useState)(null),a=(0,Z.useRef)({input:0,output:0}),o=(0,Z.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Z.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(qe),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)([]),[ee,te]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(`user`),j=(0,Z.useRef)(null),M=(0,Z.useRef)(h),N=(0,Z.useRef)(c),P=(0,Z.useRef)(T),F=(0,Z.useRef)(t);return M.current=h,N.current=c,P.current=T,F.current=t,(0,Z.useEffect)(()=>{C&&te(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:f,setActiveTool:p,captions:h,setCaptions:g,failure:_,reportFailure:(0,Z.useCallback)(t=>{v(m(t,e))},[e]),clearFailure:(0,Z.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Z.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Z.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:E,everConnected:ee,videoPreview:D,setVideoPreview:O,videoFacingMode:k,setVideoFacingMode:A,videoCaptureRef:j,captionsRef:M,isMutedRef:N,sessionPermissionsRef:P,statusRef:F,resetCaptions:(0,Z.useCallback)(()=>{g(qe())},[]),stopVideo:(0,Z.useCallback)(()=>{j.current&&=(j.current.stop(),null),O(null),A(`user`),d(!1)},[])}}function St(e){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Z.useCallback)(t=>{e.setCaptions(e=>nt(e,t)),bt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>ut(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:t=>{e.setActiveTool(e=>_t(e,t))}})},[e,o]),waitForGateDecision:(0,Z.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Z.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Z.useCallback)(()=>{a.current?.(new D(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function Ct(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function wt(e,t,n,r){r.setCaptions(r=>Qe(r,e,t,n?.interim))}async function Tt(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=x({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Et(e){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Z.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Ke({...e,options:r.options,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{Ct(e,n.current)},onTranscript:(e,t,r)=>{wt(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>Tt(e,n.current)});return t.current=i,i},[]),clearClient:(0,Z.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Dt(e,t,n,r){let[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(!1),d=(0,Z.useCallback)(t=>{u.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Z.useEffect)(()=>{n&&l(e=>e??Date.now())},[n]),(0,Z.useEffect)(()=>{n&&u.current&&(u.current=!1,e.handleToggleVideo())},[e,n]);let f=(0,Z.useCallback)(()=>{u.current=!1,e.teardownSession(),s(!0),l(null)},[e]),[p,m]=(0,Z.useState)([]),h=(0,Z.useCallback)(async()=>{let n=t.current.turns;m(e=>Je(e,n)),s(!1),l(null),await e.handleRestart()},[e,t]),g=(0,Z.useRef)(e.teardownSession);return g.current=e.teardownSession,(0,Z.useEffect)(()=>()=>{g.current()},[]),{callStarted:i,connectedAt:c,ended:o,pastCalls:p,startCall:d,handleEnd:f,handleRestart:h}}function Ot({iface:e,connection:t,...n}){let r=xt(e.labels),i=St({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Z.useRef)(t);a.current=t;let o=I(e.live.ingress,`audio`),s=I(e.live.ingress,`video`),c=I(e.live.ingress,`text`),l=(0,Z.useMemo)(()=>Oe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool?.name??null,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Z.useMemo)(h,[]),{clientRef:d,ensureClient:f,clearClient:p}=Et({options:n.options,stated:n.stated,model:n.model,effort:n.effort,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),m=gt({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,connectedAt:_,ended:v,pastCalls:y,startCall:b,handleEnd:x,handleRestart:S}=Dt(m,r.captionsRef,r.sessionActive,s),C=JSON.stringify(n.context);(0,Z.useEffect)(()=>{d.current?.setContext(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.options);(0,Z.useEffect)(()=>{d.current?.setOptions(w===void 0?void 0:JSON.parse(w))},[d,w]);let T=JSON.stringify(n.stated);return(0,Z.useEffect)(()=>{d.current?.setStated(T===void 0?void 0:JSON.parse(T))},[d,T]),dt(e.tools.page,n.pageTools),{iface:e,handle:e.identity.handle,traces:u,callStarted:g,connectedAt:_,pastCalls:y,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||v||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:x,startCall:b,handleRestart:S,handleSendText:m.handleSendText,handleToggleMic:m.handleToggleMic,handleFlipCamera:m.handleFlipCamera,handleToggleVideo:m.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=n();function kt(e){return(0,$.jsx)(R,{children:(0,$.jsx)(At,{...e})})}function At({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l,showComposer:u=!0,leading:d}){let f=L(),p=f(`@theorem.agent.handle`,{handle:e}),{blocks:m,callStarts:h}=ct(n,t),g=f(`@theorem.live.new_session`),_=Object.fromEntries(h.map(e=>[e,g])),v=u?(0,$.jsx)(ve,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l}):null;return(0,$.jsxs)(V,{height:`100%`,children:[d,(0,$.jsx)(a,{size:`fill`,children:m.length>0?(0,$.jsx)(s,{label:f(`@theorem.panel.captions.name`),children:(0,$.jsx)(fe,{blocks:m,dividers:_,handle:p,streaming:lt(t)})}):(0,$.jsx)(V,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(oe,{icon:(0,$.jsx)(o,{icon:Ee,size:`lg`,color:`secondary`}),title:f(`@theorem.panel.captions.empty.title`),description:f(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),v]})}var jt=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new D(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await v(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new D(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new D(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal,execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,background:t.background??a?.background},{vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...P(t,e.profile.labels,F)}),this.close()}}async attach(e,t,n,r,i,a={}){let o=e({send:e=>{typeof e==`string`&&this.receive(JSON.parse(e))},close:()=>this.close(),addEventListener:this.outbound.addEventListener.bind(this.outbound)},t,n,crypto.randomUUID(),r,i,{...a,clientEvents:F});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function Mt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new jt(e,t,r)}}var Nt={borderRadius:`var(--radius-chat, var(--radius-container))`};function Pt({call:e}){let t=L(),n=e.gatePrompt,r=e.resolveGateDecision,i=t(`@theorem.agent.handle`,{handle:e.handle});return(0,$.jsx)(le,{isOpen:n!==null,purpose:`required`,width:400,padding:0,style:Nt,onOpenChange:e=>{e||r({action:`deny`})},children:n?n.gate.kind===`auth`?(0,$.jsx)(E,{gate:n.gate,toolName:n.gate.tool,onAuthenticated:e=>{r({action:`auth`,secret:e})}}):(0,$.jsx)(T,{gate:n.gate,toolName:n.gate.tool,agent:i,input:n.input,onDecision:e=>{r({action:e})}}):null})}function Ft({video:e,facingMode:t}){let n=L(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,Z.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(w,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var It=720,Lt=320;function Rt({theme:e,mode:t,labels:n,...r}){return(0,$.jsx)(_,{theme:e,mode:t,children:(0,$.jsx)(R,{labels:n,children:(0,$.jsx)(zt,{...r})})})}function zt({call:e,trace:t,onMinimize:n}){let a=L(),s=(0,Z.useRef)(null),f=ue(e.iface,e.traces,t),p=u(s,!0),m={name:a(`@theorem.panel.captions.name`),show:a(`@theorem.panel.captions.show`),hide:a(`@theorem.panel.captions.hide`),resize:a(`@theorem.panel.captions.resize`)},h=(0,$.jsx)(d,{labels:m,icon:(0,$.jsx)(o,{icon:pe}),panelId:p.id,open:p.open,onToggle:p.toggle});return e.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(U,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(c,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,$.jsx)(Kt,{call:e})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(V,{height:`100%`,padding:3,children:(0,$.jsx)(Vt,{call:e,captionsToggle:h,onMinimize:n})})})})})})}),(0,$.jsx)(Pt,{call:e})]}):(0,$.jsx)(U,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Bt,{call:e})})})})}function Bt({call:e}){let t=L();return(0,$.jsx)(V,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(b,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:be,gap:8,children:[(0,$.jsxs)(V,{gap:1,children:[(0,$.jsx)(f,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(z,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(p,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(p,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(o,{icon:K}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Vt({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=Ht();return(0,$.jsx)(V,{ref:i,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:It,height:`100%`,gap:3,children:[(0,$.jsxs)(V,{gap:.5,children:[(0,$.jsx)(f,{type:`label`,color:`secondary`,children:r(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{size:`sm`,color:`secondary`,children:se(r,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(W,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(W,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(a,{size:`fill`,children:(0,$.jsx)(V,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(V,{width:`100%`,height:Lt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(ge,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Ut,{call:e,captionsToggle:t,onMinimize:n})]})})}function Ht(){let e=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Ut({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=!e.sessionActive,a=[];return e.voiceAvailable&&a.push((0,$.jsx)(H,{label:r(`@theorem.live.microphone`),tooltip:r(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:i,icon:(0,$.jsx)(o,{icon:te}),pressedIcon:(0,$.jsx)(o,{icon:we}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&a.push((0,$.jsx)(Wt,{call:e},`video`)),n&&a.push((0,$.jsx)(B,{label:r(`@theorem.live.minimize`),tooltip:r(`@theorem.live.minimize`),variant:`ghost`,icon:(0,$.jsx)(o,{icon:Se}),onClick:n},`minimize`)),a.push((0,$.jsx)(Z.Fragment,{children:t},`captions`),(0,$.jsx)(Gt,{call:e},`call`)),(0,$.jsx)(ce,{label:r(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(z,{gap:2,vAlign:`center`,children:a})})}function Wt({call:e}){let t=L(),n=!e.sessionActive;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(H,{label:t(`@theorem.live.camera`),tooltip:t(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:n,icon:(0,$.jsx)(o,{icon:K}),pressedIcon:(0,$.jsx)(o,{icon:De}),onPressedChange:()=>{e.handleToggleVideo()}}),e.isVideoOn?(0,$.jsx)(B,{label:t(`@theorem.live.flip_camera`),tooltip:t(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:n,icon:(0,$.jsx)(o,{icon:Ce}),onClick:()=>{e.handleFlipCamera()}}):null]})}function Gt({call:e}){let t=L();return e.canRestart?(0,$.jsx)(B,{label:t(`@theorem.live.start_call`),tooltip:t(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>{e.handleRestart()}}):(0,$.jsx)(B,{label:t(`@theorem.live.end_call`),tooltip:t(`@theorem.live.end_call`),variant:`destructive`,isDisabled:!e.sessionActive,icon:(0,$.jsx)(o,{icon:Te}),onClick:e.handleEnd})}function Kt({call:e}){return(0,$.jsx)(kt,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,$.jsx)(Ft,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function qt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(Yt,{...t,connect:()=>e?Mt(n,e):C(n)})}function Jt({endpoint:e,...t}){let{actingAs:n}=he();return(0,$.jsx)(Yt,{...t,connect:()=>({createSocket:()=>new WebSocket(ye(e,n))})})}function Yt({payload:e,note:t,connect:n,trace:r,options:i,stated:a,context:o}){let s=(0,Z.useMemo)(()=>g(e),[e]),c=(0,Z.useMemo)(()=>S(e),[e]);return s.type===`live`?(0,$.jsx)(Xt,{iface:s,connection:()=>(t(),n()),trace:r,options:i,stated:a,context:o,pageTools:c}):null}function Xt({trace:e,...t}){let n=Ot(t);return(0,$.jsx)(Rt,{labels:ee,call:n,trace:e})}export{Jt as ProjectLive,qt as StudioLive};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cluq4EiW.js";import{a as i}from"./fieldParts-DOfguMAs.js";import{t as a}from"./Text-BDwNaqzZ.js";import{t as o}from"./Button-98PahHB4.js";import{a as s,o as c,t as l}from"./TextInput-BRBEgg_h.js";import{t as u}from"./createReactComponent-DVEyVJ-p.js";import{t as d}from"./ScrollableArea-BGmyGfiL.js";import{a as f,n as p,o as m}from"./type-icons-DgazEJTc.js";import{n as h,t as g}from"./Center-C9ai7fq_.js";import{t as _}from"./IconSearch-BN1R3FIx.js";import{r as v,s as y,t as b}from"./tree-Bo29WGA0.js";import{F as x,i as S}from"./workspace-C7bvk7HE.js";import{i as C,n as w,r as T,t as E}from"./map-token-_aDyWhNO.js";import{i as D,n as O,o as k}from"./studio-session-ClF2iNCX.js";import{t as ee}from"./EmptyState-DVoDGbtj.js";import{t as A}from"./IconButton-Jbcy-K-d.js";import{it as j,n as M,tn as N,v as P,xt as F,yt as I}from"./index-DNFrrd7f.js";var L=u(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),R=u(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),z=u(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),B=u(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function V(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function H(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function U(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,S(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,y(e.key)])),a=x(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:S(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:S(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:H(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=S(e,t);return s.has(n)?n:S(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=v(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:S(t.key,b(i.key))});let s=S(t.key,b(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==S(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=y(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[y(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):S(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:F(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=V([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),_=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[_({label:`Providers`,nodes:V([...l.values()],n,g)}),_({label:`Shared settings`,nodes:V(p,n,m)},{label:`Models`,nodes:h}),_({label:`Profiles`,nodes:o}),_({label:`Tools`,nodes:V(f,n,m)})].filter(e=>e.length>0),links:n}}function W(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function G(e){let t=W(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function te(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function ne(e,t){let n=typeof t==`string`?[t]:t,r=G(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=W(e),r=new Map;for(let{link:i,from:a,to:o}of G(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function K(e){return e.kind===`tool`||e.kind===`shared`?2:1}var ae=24,q=8,J=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return G(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function se(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||K(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(oe(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:S,headings:w,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:ee,rails:A}=_(D),j=a/2,M=Math.max(o/2,u),N=[],P=new Map,F=Math.max(a,...y.map(e=>e*J)),I=G(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+j&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+j;return O=Math.max(O,l),[{link:e,from:t,to:n,d:T({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=ee.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(A.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?T(p,m):C(p,m,b,q),S=(e,t)=>t>e.y-M&&t<e.y+e.height+M,w=Math.abs(m.x-p.x)<F+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/ae)).some(t=>t.x>e.x&&t.x<e.x+e.width&&S(e,t.y)));if(w.length===0)return[{link:e,from:t,to:n,d:x.d}];let[I,L]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],R=e=>{let t=[...w];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-M:Math.max(...t.map(e=>e.y+e.height))+M,r=[...s,...N].filter(e=>!t.includes(e)&&e.x<L&&e.x+e.width>I&&S(e,n));if(r.length===0)return n;t.push(...r)}},z=e=>Math.abs(i.y-e)+Math.abs(o.y-e),B=`${f}:${y}`,V=P.get(B)??(()=>{let[e,t]=[R(-1),R(1)],n=e>=0&&z(e)<=z(t)?e:t;return N.push({id:``,x:I,y:n-q+M,width:L-I,height:2*(q-M)}),P.set(B,n),n})();k=Math.max(k,V);let H=d?p.x+l*J:b,U=d?b:m.x-l*J,W={x:(H+U)/2,y:V};return[{link:e,from:t,to:n,d:C(p,W,H,q).d+C(W,m,U,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:S,headings:w,lines:I}}var Y=e(t(),1),ce={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${O}.map`:`${O}.map.project:${e}`;function le(e){if(!D(e))return{};let t={};for(let[n,r]of Object.entries(e))D(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function ue(e){try{let t=JSON.parse(k()?.getItem(X(e))??`null`);return D(t)?{tokens:le(t.tokens),detail:le(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:ce}catch{return ce}}function de(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?k()?.removeItem(X(e)):k()?.setItem(X(e),JSON.stringify(t))}function fe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function pe(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var me=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function he(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=me(e.left,a.scrollWidth-a.clientWidth),r=me(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var ge=e=>e.button===0&&e.pointerType!==`touch`;function _e(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ve(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!ge(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),_e(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),ye={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},be={...ye,node:{width:240,height:84}},xe=28;function Se(e){return e.length>xe?`${e.slice(0,27)}…`:e}function Ce({kind:e,type:t,note:n}){return(e===`agent`?f(t):void 0)||(e===`tool`?m(t??``):e===`model`?P(n)??M.modelBinding:e===`provider`?N:e===`shared`&&t&&Object.hasOwn(M,t)?M[t]:e===`agent`?p.text:c)}function we(e){return Object.hasOwn(M,e)?M[e]:c}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Te=4,Ee=24,De={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function Oe(e){let t=I()?.name,[n,r]=(0,Y.useState)(()=>ue(t)),i=e=>{r(e),de(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:ne(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function ke(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!ge(o))return;let c;_e(o,(e,r)=>{!c&&Math.hypot(e,r)<Te||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?De[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Ee,0),c=Math.max(o.y+a.y*Ee,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function Ae(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{let n=new Set,r=new Set;if(t===void 0)return[n,r];n.add(t);for(let{link:i,from:a,to:o}of e.lines)if([i.from,i.to,a,o].includes(t)){r.add(i);for(let e of[i.from,i.to,a,o])n.add(e)}return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function je(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return he(n,e=>{let{left:t,top:r}=pe(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Me(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:c,tidy:l}=n,u=[];e&&e.id!==r&&u.push({label:`Show only its family`,icon:z,onClick:()=>{o(e.id)}});let d=e?.opens;d!==void 0&&u.push({label:`Open`,icon:h,onClick:()=>{t(d)}}),e&&u.push({type:`divider`});let f={label:`Show everything`,icon:s,onClick:()=>{o(void 0)}};return[...u,...r===void 0?[]:[f],{label:i?`Collapse`:`Expand`,icon:i?R:L,onClick:c},{label:`Tidy`,icon:B,isDisabled:!a,onClick:l}]}function Ne({actions:e,query:t,onQuery:n,onClose:a}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:p,tidy:m}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(l,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:_,hasClear:!0,value:t,onChange:n}),c!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:s,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:B,size:`sm`}),onClick:m}),(0,Z.jsx)(A,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:u?R:L,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:p}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Pe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(E,{id:t.id,label:Se(t.long??t.label),icon:Ce(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>xe?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:Ce(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:K(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:we(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Ie({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:c,map:l,moved:u,put:f,showFamily:p,expand:m}=Oe((0,Y.useMemo)(()=>U(e,t),[e,t])),[h,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>te(l,h),[l,h]),b=(0,Y.useMemo)(()=>h.trim()===``?l:ne(l,y),[l,h,y]),x=h.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),C=s?be:ye,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=w(S,T),D=(0,Y.useMemo)(()=>se(b,C,{moved:u,widths:E,detail:s}),[b,C,s,u,E]),O=b.columns.flat().flatMap(e=>e.nodes),k=O.find(e=>Q(e,n))?.id;je(S,c,{place:k===void 0?void 0:D.nodes[k],sizes:C});let{dragging:A,draggable:M}=ke(D,u,f),{panning:N,pan:P}=ve(`[data-map-node]`),{lit:F,on:I,onLines:L,lights:R}=Ae(D),z={family:c,expanded:s,isMoved:O.some(e=>Object.hasOwn(u,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[B,V]=(0,Y.useState)(),H=Me(O.find(e=>e.id===B),i,z),W=s?Fe:Pe,G=e=>L.has(e.link)?2:+(e.from===k||e.to===k),re=[...D.lines].sort((e,t)=>G(e)-G(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&c!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(d,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(j,{items:H,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":F===void 0||A!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:P,onContextMenuCapture:e=>{V(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(C.node.width)}px`,"--map-line":`${String(C.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:re.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":L.has(e)?``:void 0,"data-open":t===k||n===k?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(W,{node:e,place:t,joins:ie(b,e.id),selected:n,on:I,isFound:y.includes(e.id),isDragging:A===e.id,onOpen:i,lights:R,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(g,{className:`studio-map-nothing`,children:(0,Z.jsx)(ee,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:_,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Ne,{actions:z,query:h,onQuery:v,onClose:o})]})}export{Ie as StudioMap};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-C9dlIB4I.js";import{a as i}from"./fieldParts-DJZ7Rxcc.js";import{t as a}from"./Text-DfN1tSUL.js";import{t as o}from"./Button-Cb-mh6ml.js";import{t as s}from"./createReactComponent-DVEyVJ-p.js";import{t as c}from"./ScrollableArea-Db8BBKVt.js";import{a as l,n as u,o as d}from"./type-icons-DgazEJTc.js";import{a as f,i as p,t as m}from"./TextInput-CYSGEp-G.js";import{n as h,t as g}from"./Center-BVnAO8rr.js";import{t as _}from"./IconSearch-BN1R3FIx.js";import{r as v,s as y,t as b}from"./tree-Bo29WGA0.js";import{F as x,i as S}from"./workspace-C7bvk7HE.js";import{i as C,n as w,r as T,t as E}from"./map-token-CgKWabfH.js";import{i as D,n as O,o as k}from"./studio-session-ClF2iNCX.js";import{t as ee}from"./EmptyState-B_rMeBCn.js";import{t as A}from"./IconButton-Crxt9XEq.js";import{Qt as j,_ as M,_t as N,n as P,nt as F,yt as I}from"./index-C1WNmgOO.js";var L=s(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),R=s(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),z=s(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),B=s(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function V(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function H(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function U(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,S(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,y(e.key)])),a=x(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:S(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:S(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:H(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=S(e,t);return s.has(n)?n:S(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=v(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:S(t.key,b(i.key))});let s=S(t.key,b(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==S(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=y(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[y(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):S(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:I(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=V([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),_=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[_({label:`Providers`,nodes:V([...l.values()],n,g)}),_({label:`Shared settings`,nodes:V(p,n,m)},{label:`Models`,nodes:h}),_({label:`Profiles`,nodes:o}),_({label:`Tools`,nodes:V(f,n,m)})].filter(e=>e.length>0),links:n}}function W(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function G(e){let t=W(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function te(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function ne(e,t){let n=typeof t==`string`?[t]:t,r=G(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=W(e),r=new Map;for(let{link:i,from:a,to:o}of G(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function K(e){return e.kind===`tool`||e.kind===`shared`?2:1}var ae=24,q=8,J=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return G(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function se(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||K(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(oe(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:S,headings:w,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:ee,rails:A}=_(D),j=a/2,M=Math.max(o/2,u),N=[],P=new Map,F=Math.max(a,...y.map(e=>e*J)),I=G(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+j&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+j;return O=Math.max(O,l),[{link:e,from:t,to:n,d:T({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=ee.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(A.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?T(p,m):C(p,m,b,q),S=(e,t)=>t>e.y-M&&t<e.y+e.height+M,w=Math.abs(m.x-p.x)<F+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/ae)).some(t=>t.x>e.x&&t.x<e.x+e.width&&S(e,t.y)));if(w.length===0)return[{link:e,from:t,to:n,d:x.d}];let[I,L]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],R=e=>{let t=[...w];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-M:Math.max(...t.map(e=>e.y+e.height))+M,r=[...s,...N].filter(e=>!t.includes(e)&&e.x<L&&e.x+e.width>I&&S(e,n));if(r.length===0)return n;t.push(...r)}},z=e=>Math.abs(i.y-e)+Math.abs(o.y-e),B=`${f}:${y}`,V=P.get(B)??(()=>{let[e,t]=[R(-1),R(1)],n=e>=0&&z(e)<=z(t)?e:t;return N.push({id:``,x:I,y:n-q+M,width:L-I,height:2*(q-M)}),P.set(B,n),n})();k=Math.max(k,V);let H=d?p.x+l*J:b,U=d?b:m.x-l*J,W={x:(H+U)/2,y:V};return[{link:e,from:t,to:n,d:C(p,W,H,q).d+C(W,m,U,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:S,headings:w,lines:I}}var Y=e(t(),1),ce={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${O}.map`:`${O}.map.project:${e}`;function le(e){if(!D(e))return{};let t={};for(let[n,r]of Object.entries(e))D(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function ue(e){try{let t=JSON.parse(k()?.getItem(X(e))??`null`);return D(t)?{tokens:le(t.tokens),detail:le(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:ce}catch{return ce}}function de(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?k()?.removeItem(X(e)):k()?.setItem(X(e),JSON.stringify(t))}function fe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function pe(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var me=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function he(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=me(e.left,a.scrollWidth-a.clientWidth),r=me(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var ge=e=>e.button===0&&e.pointerType!==`touch`;function _e(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ve(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!ge(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),_e(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),ye={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},be={...ye,node:{width:240,height:84}},xe=28;function Se(e){return e.length>xe?`${e.slice(0,27)}…`:e}function Ce({kind:e,type:t,note:n}){return(e===`agent`?l(t):void 0)||(e===`tool`?d(t??``):e===`model`?M(n)??P.modelBinding:e===`provider`?j:e===`shared`&&t&&Object.hasOwn(P,t)?P[t]:e===`agent`?u.text:f)}function we(e){return Object.hasOwn(P,e)?P[e]:f}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Te=4,Ee=24,De={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function Oe(e){let t=N()?.name,[n,r]=(0,Y.useState)(()=>ue(t)),i=e=>{r(e),de(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:ne(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function ke(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!ge(o))return;let c;_e(o,(e,r)=>{!c&&Math.hypot(e,r)<Te||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?De[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Ee,0),c=Math.max(o.y+a.y*Ee,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function Ae(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{let n=new Set,r=new Set;if(t===void 0)return[n,r];n.add(t);for(let{link:i,from:a,to:o}of e.lines)if([i.from,i.to,a,o].includes(t)){r.add(i);for(let e of[i.from,i.to,a,o])n.add(e)}return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function je(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return he(n,e=>{let{left:t,top:r}=pe(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Me(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:s,tidy:c}=n,l=[];e&&e.id!==r&&l.push({label:`Show only its family`,icon:z,onClick:()=>{o(e.id)}});let u=e?.opens;u!==void 0&&l.push({label:`Open`,icon:h,onClick:()=>{t(u)}}),e&&l.push({type:`divider`});let d={label:`Show everything`,icon:p,onClick:()=>{o(void 0)}};return[...l,...r===void 0?[]:[d],{label:i?`Collapse`:`Expand`,icon:i?R:L,onClick:s},{label:`Tidy`,icon:B,isDisabled:!a,onClick:c}]}function Ne({actions:e,query:t,onQuery:n,onClose:a}){let{family:s,expanded:c,isMoved:l,showFamily:u,expand:d,tidy:f}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(m,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:_,hasClear:!0,value:t,onChange:n}),s!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:p,size:`sm`}),onClick:()=>{u(void 0)}}),l&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:B,size:`sm`}),onClick:f}),(0,Z.jsx)(A,{label:c?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:c?R:L,size:`sm`}),tooltip:c?`Show each node as a token`:`Show sections and descriptions`,onClick:d}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Pe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(E,{id:t.id,label:Se(t.long??t.label),icon:Ce(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>xe?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:Ce(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:K(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:we(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Ie({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:l,map:u,moved:d,put:f,showFamily:p,expand:m}=Oe((0,Y.useMemo)(()=>U(e,t),[e,t])),[h,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>te(u,h),[u,h]),b=(0,Y.useMemo)(()=>h.trim()===``?u:ne(u,y),[u,h,y]),x=h.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),C=s?be:ye,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=w(S,T),D=(0,Y.useMemo)(()=>se(b,C,{moved:d,widths:E,detail:s}),[b,C,s,d,E]),O=b.columns.flat().flatMap(e=>e.nodes),k=O.find(e=>Q(e,n))?.id;je(S,l,{place:k===void 0?void 0:D.nodes[k],sizes:C});let{dragging:A,draggable:j}=ke(D,d,f),{panning:M,pan:N}=ve(`[data-map-node]`),{lit:P,on:I,onLines:L,lights:R}=Ae(D),z={family:l,expanded:s,isMoved:O.some(e=>Object.hasOwn(d,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[B,V]=(0,Y.useState)(),H=Me(O.find(e=>e.id===B),i,z),W=s?Fe:Pe,G=e=>L.has(e.link)?2:+(e.from===k||e.to===k),re=[...D.lines].sort((e,t)=>G(e)-G(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&l!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(c,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(F,{items:H,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":P===void 0||A!==void 0?void 0:``,"data-panning":M?``:void 0,onPointerDown:N,onContextMenuCapture:e=>{V(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(C.node.width)}px`,"--map-line":`${String(C.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:re.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":L.has(e)?``:void 0,"data-open":t===k||n===k?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(W,{node:e,place:t,joins:ie(b,e.id),selected:n,on:I,isFound:y.includes(e.id),isDragging:A===e.id,onOpen:i,lights:R,drag:j(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(g,{className:`studio-map-nothing`,children:(0,Z.jsx)(ee,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:_,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Ne,{actions:z,query:h,onQuery:v,onClose:o})]})}export{Ie as StudioMap};
@@ -0,0 +1,3 @@
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./StackItem-ClAjT294.js";import{t as i}from"./Icon-C9dlIB4I.js";import{a}from"./fieldParts-DJZ7Rxcc.js";import{t as o}from"./Text-DfN1tSUL.js";import{t as s}from"./Button-Cb-mh6ml.js";import{_ as c,a as l,f as u,g as d,o as f,p,s as m}from"./browser-transport-DVnbvtNO.js";import{i as h,r as g}from"./row-keys-0Bn7ZyYy.js";import{g as _,t as v}from"./studio-labels-EQRWPOr5.js";import{t as y}from"./IconHistory-DdcWdeRG.js";import{c as b}from"./host-patterns-F-KZIzkF.js";import{T as x}from"./shaped-data-CtJtZSw9.js";import{n as S}from"./trace-record-C-Opk3HK.js";import{n as C}from"./trace-schema--4IGmLeE.js";import{v as w}from"./turn-client-CobwqNwm.js";import{n as T,t as E}from"./labels-provider-Bv9WPagB.js";import{t as D}from"./HStack-D3i0gAme.js";import{t as O}from"./IconButton-Crxt9XEq.js";import{t as k}from"./VStack-BGVV0uKl.js";import{a as A,i as j,o as M,t as N}from"./ConsoleFrame-CYYtfWNI.js";import{A as ee,B as te,C as ne,F as re,M as ie,_t as ae,a as oe,c as se,gt as ce,j as le,qt as ue,w as P}from"./index-C1WNmgOO.js";var F=e=>typeof e==`object`&&!!e&&!Array.isArray(e),I=(e,t)=>e.attributes[t],L=(e,t)=>{let n=I(e,t);return typeof n==`string`?n:void 0};function R(e,t,n){let r=I(t,n);return r===void 0?void 0:S(e,r)}function z(e,t,n){let r=R(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function B(e,t,n){let r=R(e,t,n);return Array.isArray(r)?r.filter(F):[]}var V=e=>Array.isArray(e.parts)?e.parts.filter(F):[],H=e=>BigInt(String(e.startTimeUnixNano)),U=(e,t)=>{let n=H(e)-H(t);return n===0n?0:n<0n?-1:1};function W(e){let t=e.endTimeUnixNano;if(!t)return;let n=H(e),r=BigInt(String(t));if(r<=n)return;let i=Number(n/1000000n),a=Number(r/1000000n);if(!(!Number.isFinite(i)||!Number.isFinite(a)||a<=i))return{startedAt:i,endedAt:a}}function de(e){let t=W(e);if(t)return{workedMs:t.endedAt-t.startedAt,endedAt:t.endedAt}}function fe(e,t){let n=de(t);if(!n)return e;let r=e.findLastIndex(e=>e.kind===`turn-done`);return r<0?e:e.map((e,t)=>t===r?{...e,...n}:e)}var pe=e=>`content_sha256`in e||`json_sha256`in e;function G(e){let t=e.arguments;if(F(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return F(e)?e:{}}catch{return{}}}function K(e){if(typeof e.content==`string`){if(e.type===`reasoning`)return{type:`thought`,text:e.content};if(e.type===`text`)return{type:`text`,text:e.content}}}function me(e){let t=[],n=[],r=!1;for(let i of e){let e=V(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=K(i);pe(i)?r=!0:e?t.push(e):i.type===`structured`&&!a?t.push({type:`text`,text:JSON.stringify(i.content)}):i.type===`tool_call`&&typeof i.name==`string`?(n.push(i.name),t.push({type:`tool`,tool:{name:i.name,callId:typeof i.id==`string`?i.id:`replay-${String(n.length)}`,arguments:G(i)}})):(i.type===`blob`||i.type===`uri`)&&(r=!0)}}return{events:t,calls:n,missing:r}}function he(e,t){for(let n=e;n;n=t.get(n.parentSpanId??``)){let e=L(n,`gen_ai.agent.name`);if(L(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var q=e=>L(e,`gen_ai.operation.name`);function ge(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>q(e)===`chat`).toSorted(U).map(n=>{let r=me(B(e,n,`gen_ai.output.messages`)),i=L(n,`theorem.stop.kind`)??`completed`;return{agent:he(n,t),...r,events:[...r.events,{type:`done`,stop:{kind:i}}]}})}function _e(e){return e.spans.filter(e=>q(e)===`execute_tool`).toSorted(U).map(t=>({name:L(t,`gen_ai.tool.name`)??``,result:z(e,t,`gen_ai.tool.call.result`),failed:L(t,`theorem.tool.outcome`)===`error`}))}function J(e,t){let n=B(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?V(n):[];return{text:r.flatMap(e=>e.type===`text`&&typeof e.content==`string`?[e.content]:[]).join(`
2
+ `),attachments:r.filter(e=>e.type===`blob`||e.type===`uri`).length}}function ve(e,t){let n=[];for(let r of t.events??[]){if(r.name!==`theorem.grounding`)continue;let i=r.attributes.sources;if(i===void 0)continue;let a=S(e,i);if(!Array.isArray(a))continue;let o=[];for(let e of a)F(e)&&typeof e.title==`string`&&typeof e.uri==`string`&&o.push({title:e.title,uri:e.uri,type:e.type===`maps`?`maps`:`web`,...typeof e.placeId==`string`?{placeId:e.placeId}:{}});if(o.length){let e=L(t,`gen_ai.tool.call.id`);n.push({type:`citation`,sources:o,...e?{callId:e}:{}})}}return n}function ye(e,t){let n=e.spans.filter(e=>q(e)===`execute_tool`).toSorted(U),r=new Set,i=(e,t)=>{let i=n.find(t=>L(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&L(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of B(e,t,`gen_ai.output.messages`))for(let t of V(n)){let n=K(t);if(n)a.push(n);else if(t.type===`structured`&&t.content!==void 0)a.push({type:`structured`,structured:t.content});else if(t.type===`tool_call`&&typeof t.name==`string`){let n=typeof t.id==`string`?t.id:`call-${String(a.length)}`;a.push(...be(e,t.name,n,G(t),i))}}let o=z(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=L(t,`theorem.stop.kind`)??`completed`;return a.push({type:`done`,stop:{kind:s}}),a}function be(e,t,n,r,i){let a=i(n,t),o={type:`tool`,tool:{name:t,callId:n,arguments:r}};if(!a)return[o];let s=W(a),c=s?.startedAt??Number(H(a)/1000000n),l=s?.endedAt??c,u=z(e,a,`gen_ai.tool.call.result`),d=L(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:L(a,`theorem.tool.failure.code`)??`failed`,kind:`internal`,message:u},readBack:u}:{phase:`complete`,output:xe(e,a,u),readBack:u};return[o,{type:`tool`,tool:{name:t,callId:n,phase:`running`,at:c}},{type:`tool`,tool:{name:t,callId:n,at:l,...d}},...ve(e,a)]}function xe(e,t,n){return`theorem.tool.data`in t.attributes?R(e,t,`theorem.tool.data`):Se(n)}function Se(e){try{return JSON.parse(e)}catch{return e}}var Ce=(e,t)=>`${e}:${t}`;function we(e,t){if(!t.events.some(e=>e.name===`theorem.compaction`))return!1;let n=J(e,t);return!n.text&&n.attachments===0}function Te(e){let t=new Map,n=new Map,r=(e,t)=>{for(let r of e.spans)n.set(Ce(r.traceId,r.spanId),t);t.script.records.push(e)};return e.forEach((e,i)=>{let a=x(e);if(!a||q(a)!==`invoke_agent`||we(e,a))return;let o=ge(e),s=_e(e),c=a.parentSpanId?n.get(Ce(a.traceId,a.parentSpanId)):void 0;if(c){c.turn.calls.push(...o),c.turn.results.push(...s),r(e,c);return}let l=L(a,`gen_ai.agent.name`)??``,u=L(a,`gen_ai.conversation.id`),d=`${l}\u0000${u??``}`,f=t.get(d);f||(f={agent:l,...u===void 0?{}:{conversation:u},turns:[],records:[],recordedAt:Number(H(a)/1000000n)},t.set(d,f));let p=J(e,a),m={...p,calls:o,results:s,blocks:fe(w({text:p.text},ye(e,a),{idPrefix:`recorded-${String(i)}`}),a)};f.turns.push(m),r(e,{turn:m,script:f})}),[...t.values()]}function Ee(e){if(e.failed)throw Error(e.result);let t=Se(e.result);return F(t)?t:{result:t}}var De=e=>{let t=e%100,n=t>=11&&t<=13?`th`:{1:`st`,2:`nd`,3:`rd`}[e%10]??`th`;return`${String(e)}${n}`};function Oe(e,t,n){if(!e)return`The profile asked the model a ${De(t+1)} time this turn; the recording answered ${String(t)}.`;if(e.missing)return`The recording does not hold all of this reply.`;let r=new Set((n.wireTools??[]).map(e=>e.name)),i=e.calls.find(e=>!r.has(e));return i&&`The recording calls ${i}, which the profile no longer offers.`}function ke(e,t,n){let r=0,i=new Map,a=new Map,o=t=>{let n=a.get(t);if(!n){n=new Map;for(let r of e.turns[t]?.results??[])n.set(r.name,[...n.get(r.name)??[],r]);a.set(t,n)}return n},s=t=>({async*complete(a){let o=e.turns[r]?.calls.filter(e=>e.agent===t)??[],s=`${String(r)} ${t}`,c=i.get(s)??0;i.set(s,c+1);let l=Oe(o[c],o.length,a);if(l)throw n({turn:r,agent:t,call:c+1,reason:l}),new b(`request`,`Replay stopped: ${l}`);yield*o[c]?.events??[]}}),c=e=>()=>{let t=o(r).get(e)?.shift();if(!t){let t=`The recording has no further result for ${e}.`;throw n({turn:r,tool:e,reason:t}),new b(`request`,`Replay stopped: ${t}`)}return Ee(t)},l=new Set(e.turns.flatMap(e=>e.results.map(e=>e.name)));return{provider:n=>s(n.id===t?e.agent:n.id),toolHandlers:Object.fromEntries([...l].map(e=>[e,c(e)])),startTurn:e=>{r=e}}}function Ae(e){return e.map(e=>{if(e.type===`agent`)return e;let{name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s}=e;return{type:`function`,name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s,inputSchema:e.inputSchema,outputSchema:e.outputSchema,...e.labels?{labels:e.labels}:{},...e.background?{background:e.background}:{}}})}function je(e){return{...e,customTools:Ae(e.customTools),...e.dependencies?{dependencies:e.dependencies.map(e=>({...e,customTools:Ae(e.customTools)}))}:{}}}function Me(e){return e.turns.flatMap(e=>e.blocks)}function Ne(e,t){let n=C.safeParse(e);if(n.success)return n.data;let r=F(e)?e.v:void 0,i=typeof r==`number`&&r!==3?`This trace is version ${String(r)}${t}; the studio reads version 3.`:`This file is not a Theorem trace${t}.`;throw new b(`request`,i)}function Pe(e){let t=Array.isArray(e)?e:[e];return t.map((e,n)=>Ne(e,t.length>1?` (record ${String(n+1)})`:``))}function Fe(e){try{return Pe(JSON.parse(e))}catch(e){if(e instanceof b)throw e}let t=e.split(`
3
+ `).map((e,t)=>({line:e,at:t+1})).filter(({line:e})=>e.trim());if(t.length<2)throw new b(`request`,`This file is not JSON.`);return t.map(({line:e,at:t})=>{let n;try{n=JSON.parse(e)}catch{throw new b(`request`,`Line ${String(t)} of this file is not JSON.`)}return Ne(n,` (line ${String(t)})`)})}var Y=e(t(),1),X=n();function Ie(e,t,n){return t?f(e,t,{conversationKey:oe(),blocks:n}):u(e,n)}var Z=e=>`turn ${String(e+1)}`;function Q({iface:e,feed:t,trace:n,card:r,conversation:i}){let a=ee(e,t,n);return(0,X.jsxs)(N,{inspector:a,maxWidth:`960px`,requestLabel:`Trace`,children:[r,i]})}function Le({iface:e,blocks:t,banner:n,chat:r}){let i=T();return(0,X.jsxs)(A,{label:`Conversation`,children:[n,(0,X.jsx)(re,{blocks:t,handle:i(`@theorem.agent.handle`,{handle:e.identity.handle}),labels:e.labels,streaming:r?.streaming,delivery:r?.delivery,answering:r?.answering,onToolDecision:r&&((e,t)=>{r.handleToolDecision(e,t)}),onAuthenticated:r&&((e,t)=>{r.handleAuthenticated(e,t)})})]})}function Re({onImport:e}){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useState)(!1);return(0,X.jsxs)(k,{gap:2,children:[(0,X.jsx)(ie,{label:`Trace file`,isLabelHidden:!0,mode:`dropzone`,accept:`application/json,.json,.jsonl`,isLoading:r,placeholder:`Drop a trace (.json or .jsonl) or choose a file`,value:null,changeAction:async t=>{let r=Array.isArray(t)?t[0]:t;if(r){i(!0);try{let t=Fe(await r.text());e({name:r.name,records:t}),n(void 0)}catch(e){n(e instanceof Error?e.message:String(e))}finally{i(!1)}}},onChange:()=>void 0}),t?(0,X.jsx)(P,{status:`error`,title:t}):null]})}var ze=e=>e.recordedAt===void 0?void 0:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(e.recordedAt);function Be({shown:e,onShown:t}){return(0,X.jsx)(te,{label:`Replayed`,tooltip:e===`replayed`?`Recorded`:`Replayed`,size:`sm`,isIconOnly:!0,icon:(0,X.jsx)(i,{icon:y,size:`sm`}),pressedIcon:(0,X.jsx)(i,{icon:ue,size:`sm`}),isPressed:e===`replayed`,onPressedChange:e=>{t(e?`replayed`:`recorded`)}})}function Ve({controls:e}){let{script:t,payload:n}=e,s=t.turns.length,c=[t.agent||`No agent`,`${String(s)} ${s===1?`turn`:`turns`}`,ze(t)];return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(D,{gap:2,vAlign:`center`,children:[(0,X.jsx)(r,{size:`fill`,children:(0,X.jsxs)(k,{gap:0,children:[(0,X.jsx)(o,{type:`label`,maxLines:1,children:e.opened.name}),(0,X.jsx)(o,{type:`supporting`,color:`secondary`,maxLines:1,children:c.filter(Boolean).join(` · `)})]})}),(0,X.jsx)(O,{label:`Clear trace`,variant:`ghost`,size:`sm`,icon:(0,X.jsx)(i,{icon:a,size:`sm`}),isDisabled:e.isRunning,onClick:e.onClear})]}),e.count>1?(0,X.jsxs)(D,{gap:1,vAlign:`center`,children:[(0,X.jsx)(O,{label:`Previous conversation`,variant:`ghost`,size:`sm`,icon:(0,X.jsx)(i,{icon:h,size:`sm`}),isDisabled:e.isRunning||e.picked===0,onClick:()=>{e.onPick(e.picked-1)}}),(0,X.jsxs)(o,{type:`supporting`,children:[`Conversation `,String(e.picked+1),` of `,String(e.count)]}),(0,X.jsx)(O,{label:`Next conversation`,variant:`ghost`,size:`sm`,icon:(0,X.jsx)(i,{icon:g,size:`sm`}),isDisabled:e.isRunning||e.picked===e.count-1,onClick:()=>{e.onPick(e.picked+1)}})]}):null,t.agent&&t.agent!==n.profile.id?(0,X.jsx)(P,{status:`info`,title:`Recorded with ${t.agent}; a replay runs through ${n.profile.id}.`}):null,s===0?(0,X.jsx)(P,{status:`info`,title:`This trace holds no conversation to replay.`}):null,(0,X.jsx)(le,{label:`Live tools`,description:`Run the profile's tools instead of answering them from the recording.`,value:e.liveTools,onChange:e.onLiveTools})]})}var He=()=>void 0;function $({onImport:e,controls:t}){let n=t?.onReplay??He;return(0,X.jsxs)(j,{title:`Trace`,onRun:n,actions:t?.shown?(0,X.jsx)(Be,{shown:t.shown,onShown:t.onShown}):null,children:[(0,X.jsx)(Re,{onImport:e}),t?(0,X.jsx)(Ve,{controls:t}):null,(0,X.jsx)(M,{note:t?`Answers each model call from the recording, so it needs no keys.`:null,isReady:(t?.script.turns.length??0)>0,isRunning:t?.isRunning??!1,runLabel:t?.shown?`Replay again`:`Replay`,runningLabel:`Replaying`,stopLabel:`Stop`,onRun:n,onStop:t?.onStop??He})]})}function Ue({status:e,turns:t,onContinue:n,onLive:r}){let[i,a]=(0,Y.useState)(!1),[o,c]=(0,Y.useState)(),l=e=>(0,X.jsx)(s,{label:`Continue live`,variant:`secondary`,size:`sm`,isLoading:i,onClick:async()=>{a(!0),c(void 0);try{await r(e)}catch(e){c(e instanceof Error?e.message:String(e)),a(!1)}}}),u=(()=>{switch(e.kind){case`running`:return(0,X.jsx)(P,{status:`info`,title:`Replaying ${Z(e.turn)} of ${String(t)}`});case`waiting`:return(0,X.jsx)(P,{status:`info`,title:`${Z(e.turn-1)} waits on you`,description:`Answer it in the conversation, then continue the replay.`,endContent:(0,X.jsx)(s,{label:`Continue replay`,variant:`secondary`,size:`sm`,onClick:()=>{n(e.turn)}})});case`missing`:return(0,X.jsx)(P,{status:`warning`,title:`Replay stopped before ${Z(e.turn)}`,description:`It was sent with files, and a trace never holds a file's bytes. Continue live to send it again with yours.`,endContent:l(e.turn)});case`diverged`:{let t=e.divergence,n=`tool`in t?`the ${t.tool} tool`:`${t.agent}'s model call ${String(t.call)}`;return(0,X.jsx)(P,{status:`warning`,title:`Replay stopped at ${Z(t.turn)}, ${n}`,description:t.reason,endContent:l(t.turn)})}case`stopped`:return(0,X.jsx)(P,{status:`info`,title:`Replay stopped at ${Z(e.turn)}`,description:`You stopped it. Continue live to go on from here with the profile's model.`,endContent:l(e.turn)});case`failed`:return(0,X.jsx)(P,{status:`error`,title:`Replay stopped at ${Z(e.turn)}`,description:e.message,endContent:l(e.turn)});case`done`:return(0,X.jsx)(P,{status:`success`,title:`Replayed ${String(t)} ${t===1?`turn`:`turns`}`,description:`Every model call this profile made was one the recording answered.`})}})();return(0,X.jsxs)(k,{gap:1,children:[u,o?(0,X.jsx)(P,{status:`error`,title:o}):null]})}function We({payload:e,iface:t,trace:n,card:r,records:i,script:a,shown:o,liveTools:s,runtime:u,onLive:f}){let p=ae(),{actingAs:m}=se(),h=(0,Y.useRef)(void 0),[g,v]=(0,Y.useState)({kind:`running`,turn:0}),[y]=(0,Y.useState)(d),b=(0,Y.useMemo)(()=>c(i),[i]),x=(0,Y.useMemo)(()=>ke(a,e.profile.id,e=>{h.current??=e}),[a,e.profile.id]),S=(0,Y.useMemo)(()=>l(s?e:je(e),{mode:`byok`,provider:x.provider,...s?{}:{toolHandlers:x.toolHandlers}},{conversationKey:oe(),traces:y}),[e,x,s,y]),C=(0,Y.useMemo)(()=>s?_(e):void 0,[s,e]),w=ne({transport:S,iface:t,pageTools:C}),{sendText:T,handleStop:E}=w,D=(0,Y.useRef)(w.phase);D.current=w.phase;let[O,k]=(0,Y.useState)(0),A=(0,Y.useRef)(!1),j=(0,Y.useRef)(E);j.current=E,(0,Y.useEffect)(()=>()=>j.current(),[]),(0,Y.useEffect)(()=>{let e=!1,t=async()=>{for(;!e&&D.current===`streaming`;)await new Promise(e=>requestAnimationFrame(e))};return(async()=>{for(let n=O;n<a.turns.length;n+=1){if(await t(),e||A.current)return;if(D.current===`gated`)return x.startTurn(n-1),v({kind:`waiting`,turn:n});let{text:r,attachments:i}=a.turns[n];if(i>0)return v({kind:`missing`,turn:n});x.startTurn(n),v({kind:`running`,turn:n});try{let t=await T(r);if(e||A.current)return;if(h.current)return v({kind:`diverged`,divergence:h.current});t||--n}catch(e){let t=e instanceof Error?e.message:String(e);return v({kind:`failed`,turn:n,message:t})}}v({kind:`done`})})(),()=>{e=!0}},[O,x,a,T]);let M=async t=>{let n=a.turns.slice(0,t).flatMap(e=>e.blocks);f({...p?await ce(p,e.agentId,n,m):await Ie(e,u,n),text:a.turns[t]?.text??``})},N=o===`replayed`;return(0,X.jsx)(Q,{iface:t,feed:N?y:b,trace:n,card:r({isRunning:g.kind===`running`,onStop:()=>{A.current=!0,E(),v(e=>e.kind===`running`?{kind:`stopped`,turn:e.turn}:e)}}),conversation:(0,X.jsx)(Le,{iface:t,blocks:N?[...w.blocks,...w.streamBlocks]:Me(a),chat:N?w:void 0,banner:N?(0,X.jsx)(Ue,{status:g,turns:a.turns.length,onContinue:k,onLive:M}):void 0})})}function Ge(e){return(0,X.jsx)(m,{children:(0,X.jsx)(E,{labels:v,children:(0,X.jsx)(Je,{...e})})})}var Ke={agent:``,turns:[],records:[]};function qe(e,t,n){if(t.length<=1||!n)return e;let r=new Set(t.flatMap(e=>e.records)),i=new Set(n.records);return e.filter(e=>i.has(e)||!r.has(e))}function Je({payload:e,trace:t,runtime:n,onLive:r,opened:i,onOpened:a,onClear:o}){let s=(0,Y.useMemo)(()=>p(e),[e]),l=(0,Y.useMemo)(()=>i?Te(i.records):[],[i]),[u,d]=(0,Y.useState)(),f=u&&u.of===i?u.index:0,m=i?l[f]??Ke:void 0,h=(0,Y.useMemo)(()=>qe(i?.records??[],l,m),[i,l,m]),g=(0,Y.useMemo)(()=>c(h),[h]),[_,v]=(0,Y.useState)(),[y,b]=(0,Y.useState)(!1),x=_&&_.of===m&&_.agent===e.profile.id?_:void 0,S=x?.attempt??0,C=x?.shown??`recorded`,w=e=>{x&&v({...x,shown:e})},T=()=>{m&&v({of:m,agent:e.profile.id,attempt:S+1,shown:`replayed`})};if(s.type===`live`)return null;if(!i||!m)return(0,X.jsx)(Q,{iface:s,feed:g,trace:t,card:(0,X.jsx)($,{onImport:a}),conversation:null});let E=({isRunning:t,onStop:n})=>(0,X.jsx)($,{onImport:a,controls:{opened:i,script:m,picked:f,count:l.length,onPick:e=>{d({of:i,index:e})},payload:e,shown:S>0?C:null,onShown:w,liveTools:y,onLiveTools:e=>{b(e),S>0&&T()},isRunning:t,onReplay:T,onStop:n,onClear:o}});return S===0?(0,X.jsx)(Q,{iface:s,feed:g,trace:t,card:E({isRunning:!1,onStop:()=>void 0}),conversation:(0,X.jsx)(Le,{iface:s,blocks:Me(m)})}):(0,X.jsx)(We,{payload:e,iface:s,trace:t,card:E,records:h,script:m,shown:C,liveTools:y,runtime:n,onLive:r},S)}export{Ge as TraceReplay};
@@ -1 +1 @@
1
- import{l as e,r as t}from"./themeProps-Bo2jNkIC.js";import{S as n,T as r,t as i}from"./Icon-Cluq4EiW.js";import{t as a}from"./Button-98PahHB4.js";var o={"@astryx.inputClearButton.tooltip":`Clear`},s=e();r(o);var c={button:{kZKoxP:`x1qx5ct2`,kmuXW:`x2lah0s`,kVAEAm:`x1n2onr6`,"--_input-clear-hit-inset":`xtoycft x181bpwf`,"--_input-clear-hit-content":`xqxtgf4 xp8r40j`,k5JduY:`xh3pasq`,kwXMNM:`x1j6awrg`,kv0HGH:`xht581f`,$$css:!0}};function l({label:e,tooltip:n,onClick:r,onPointerDown:o,onClickCapture:l,xstyle:u,iconClassName:d}){let{className:f}=t(`input-clear-icon`),{className:p}=t(`input-clear-button`);return(0,s.jsx)(a,{variant:`ghost`,size:`sm`,label:e,tooltip:n,className:p,icon:(0,s.jsx)(i,{icon:`close`,size:`sm`,color:`secondary`,className:d==null?f:`${f} ${d}`}),onPointerDown:e=>{e.preventDefault(),o?.(e)},onMouseDown:e=>e.preventDefault(),onClick:r,onClickCapture:l,isIconOnly:!0,xstyle:[c.button,u]})}function u(e){let t=n();return l({...e,tooltip:t(`@astryx.inputClearButton.tooltip`)})}function d(e){let t=n();return l({...e,tooltip:t(`@astryx.inputClearButton.tooltip`)})}u.displayName=`InputClearButton`;export{d as n,u as t};
1
+ import{l as e,r as t}from"./themeProps-Bo2jNkIC.js";import{S as n,T as r,t as i}from"./Icon-C9dlIB4I.js";import{t as a}from"./Button-Cb-mh6ml.js";var o={"@astryx.inputClearButton.tooltip":`Clear`},s=e();r(o);var c={button:{kZKoxP:`x1qx5ct2`,kmuXW:`x2lah0s`,kVAEAm:`x1n2onr6`,"--_input-clear-hit-inset":`xtoycft x181bpwf`,"--_input-clear-hit-content":`xqxtgf4 xp8r40j`,k5JduY:`xh3pasq`,kwXMNM:`x1j6awrg`,kv0HGH:`xht581f`,$$css:!0}};function l({label:e,tooltip:n,onClick:r,onPointerDown:o,onClickCapture:l,xstyle:u,iconClassName:d}){let{className:f}=t(`input-clear-icon`),{className:p}=t(`input-clear-button`);return(0,s.jsx)(a,{variant:`ghost`,size:`sm`,label:e,tooltip:n,className:p,icon:(0,s.jsx)(i,{icon:`close`,size:`sm`,color:`secondary`,className:d==null?f:`${f} ${d}`}),onPointerDown:e=>{e.preventDefault(),o?.(e)},onMouseDown:e=>e.preventDefault(),onClick:r,onClickCapture:l,isIconOnly:!0,xstyle:[c.button,u]})}function u(e){let t=n();return l({...e,tooltip:t(`@astryx.inputClearButton.tooltip`)})}function d(e){let t=n();return l({...e,tooltip:t(`@astryx.inputClearButton.tooltip`)})}u.displayName=`InputClearButton`;function f({enterKeyHint:e,inputMode:t,autoCapitalize:n,hasAutoCorrect:r}){let i={};return e!=null&&(i.enterKeyHint=e),t!=null&&(i.inputMode=t),n!=null&&(i.autoCapitalize=n),r!=null&&(i.autoCorrect=r?`on`:`off`),i}export{u as n,d as r,f as t};
@@ -1 +1 @@
1
- import{l as e}from"./themeProps-Bo2jNkIC.js";import{t}from"./StackItem-ClAjT294.js";import{t as n}from"./Text-BDwNaqzZ.js";import{t as r}from"./HStack-CqE4exX9.js";import{t as i}from"./VStack-CCYGIv4A.js";import{t as a}from"./Card-DKuxiCN0.js";var o=e(),s={clear:`light-dark(#0d1e37, #b4c6e2)`,shade1:`light-dark(#3b5580, #6582ad)`,shade2:`light-dark(#7f95b7, #3b5078)`,shade3:`light-dark(#bcc8da, #22345a)`,failed:`light-dark(#8e2a28, #cd5f55)`},c=`light-dark(#e4e7ec, #2b2f36)`,l=`light-dark(#9aa3b1, #6b727d)`,u=s.clear,d=`var(--color-background-surface)`,f={model:`clear`,tool:`hatch`,host:`shade1`,theorem:`shade2`,user:`shade3`,error:`failed`};function p(e){return e===`hatch`?`url(#trace-fill-hatch)`:s[e]}function m(){return(0,o.jsx)(`svg`,{"aria-hidden":!0,width:0,height:0,style:{position:`absolute`},children:(0,o.jsx)(`defs`,{children:(0,o.jsxs)(`pattern`,{id:`trace-fill-hatch`,width:3,height:3,patternUnits:`userSpaceOnUse`,patternTransform:`rotate(45)`,children:[(0,o.jsx)(`rect`,{width:3,height:3,fill:c}),(0,o.jsx)(`line`,{x1:0,y1:0,x2:0,y2:3,stroke:l,strokeWidth:1.2})]})})})}function h({fill:e}){return(0,o.jsx)(`svg`,{"aria-hidden":!0,width:10,height:10,style:{display:`block`,flexShrink:0},children:(0,o.jsx)(`rect`,{width:10,height:10,rx:2,fill:p(e)})})}var g={background:`var(--theorem-console-card, var(--color-background-surface))`,borderRadius:`var(--radius-page)`};function _({title:e,value:a,note:s,aside:c,detail:l,children:d}){let f=(0,o.jsx)(n,{type:`supporting`,color:`secondary`,children:e}),p=l?(0,o.jsxs)(i,{gap:1,children:[f,(0,o.jsx)(n,{type:`supporting`,maxLines:2,children:l})]}):f;return(0,o.jsxs)(i,{gap:3,children:[c?(0,o.jsxs)(r,{gap:3,vAlign:`center`,children:[(0,o.jsx)(t,{size:`fill`,children:p}),c]}):p,(0,o.jsxs)(`div`,{style:{display:`flex`,alignItems:`baseline`,flexWrap:`wrap`,columnGap:8},children:[(0,o.jsx)(n,{size:`2xl`,weight:`medium`,hasTabularNumbers:!0,children:a}),s?(0,o.jsx)(n,{type:`supporting`,hasTabularNumbers:!0,children:(0,o.jsx)(`span`,{style:{color:u},children:s})}):null]}),d]})}function v(e){return(0,o.jsx)(a,{variant:`muted`,padding:4,style:g,children:(0,o.jsx)(_,{...e})})}export{d as a,p as c,v as i,g as n,m as o,_ as r,h as s,f as t};
1
+ import{l as e}from"./themeProps-Bo2jNkIC.js";import{t}from"./StackItem-ClAjT294.js";import{t as n}from"./Text-DfN1tSUL.js";import{t as r}from"./HStack-D3i0gAme.js";import{t as i}from"./VStack-BGVV0uKl.js";import{t as a}from"./Card-BUIbjVIe.js";var o=e(),s={clear:`light-dark(#0d1e37, #b4c6e2)`,shade1:`light-dark(#3b5580, #6582ad)`,shade2:`light-dark(#7f95b7, #3b5078)`,shade3:`light-dark(#bcc8da, #22345a)`,failed:`light-dark(#8e2a28, #cd5f55)`},c=`light-dark(#e4e7ec, #2b2f36)`,l=`light-dark(#9aa3b1, #6b727d)`,u=s.clear,d=`var(--color-background-surface)`,f={model:`clear`,tool:`hatch`,host:`shade1`,theorem:`shade2`,user:`shade3`,error:`failed`};function p(e){return e===`hatch`?`url(#trace-fill-hatch)`:s[e]}function m(){return(0,o.jsx)(`svg`,{"aria-hidden":!0,width:0,height:0,style:{position:`absolute`},children:(0,o.jsx)(`defs`,{children:(0,o.jsxs)(`pattern`,{id:`trace-fill-hatch`,width:3,height:3,patternUnits:`userSpaceOnUse`,patternTransform:`rotate(45)`,children:[(0,o.jsx)(`rect`,{width:3,height:3,fill:c}),(0,o.jsx)(`line`,{x1:0,y1:0,x2:0,y2:3,stroke:l,strokeWidth:1.2})]})})})}function h({fill:e}){return(0,o.jsx)(`svg`,{"aria-hidden":!0,width:10,height:10,style:{display:`block`,flexShrink:0},children:(0,o.jsx)(`rect`,{width:10,height:10,rx:2,fill:p(e)})})}var g={background:`var(--theorem-console-card, var(--color-background-surface))`,borderRadius:`var(--radius-page)`};function _({title:e,value:a,note:s,aside:c,detail:l,children:d}){let f=(0,o.jsx)(n,{type:`supporting`,color:`secondary`,children:e}),p=l?(0,o.jsxs)(i,{gap:1,children:[f,(0,o.jsx)(n,{type:`supporting`,maxLines:2,children:l})]}):f;return(0,o.jsxs)(i,{gap:3,children:[c?(0,o.jsxs)(r,{gap:3,vAlign:`center`,children:[(0,o.jsx)(t,{size:`fill`,children:p}),c]}):p,(0,o.jsxs)(`div`,{style:{display:`flex`,alignItems:`baseline`,flexWrap:`wrap`,columnGap:8},children:[(0,o.jsx)(n,{size:`2xl`,weight:`medium`,hasTabularNumbers:!0,children:a}),s?(0,o.jsx)(n,{type:`supporting`,hasTabularNumbers:!0,children:(0,o.jsx)(`span`,{style:{color:u},children:s})}):null]}),d]})}function v(e){return(0,o.jsx)(a,{variant:`muted`,padding:4,style:g,children:(0,o.jsx)(_,{...e})})}export{d as a,p as c,v as i,g as n,m as o,_ as r,h as s,f as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cluq4EiW.js";import{t as i}from"./Text-BDwNaqzZ.js";import{b as a,w as o}from"./browser-transport-_E7cXrRm.js";import{t as s}from"./Tooltip-Dhy5lIDA.js";import{d as c}from"./reader-DhyhAoss.js";import{n as l,o as u}from"./labels-provider-W8DCgjbB.js";import{t as d}from"./useLocale-d7ARRGFj.js";import{t as f}from"./HStack-CqE4exX9.js";import{t as p}from"./IconButton-Jbcy-K-d.js";import{t as m}from"./VStack-CCYGIv4A.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-DIxyRKED.js";import{c as y,i as b}from"./trace-patterns-DFMwRU00.js";import{n as x}from"./studio-console-Cdmx1jE7.js";import{B as S,st as C,ut as w,z as T}from"./index-DNFrrd7f.js";var E=e(t(),1),D=n(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:r}){let a=l(),o=A(),s=Object.entries(r.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:r.choice,note:a(`@theorem.decision.confidence`,{percent:o.percent.format(r.confidence)}),children:(0,D.jsx)(m,{gap:2,role:`list`,children:s.map(([e,t])=>(0,D.jsxs)(m,{gap:1,role:`listitem`,"aria-label":a(`@theorem.decision.option`,{label:e,percent:o.percent.format(t)}),children:[(0,D.jsxs)(f,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(i,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(i,{type:`supporting`,hasTabularNumbers:!0,children:o.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===r.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:r,labels:a}){let o=l(),s=A(),c=a.length,u=Math.min(c-1,Math.max(0,Math.round(r.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[u]===void 0?s.decimal.format(r.score):F(a[u]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(r.score),max:s.decimal.format(c-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(r.confidence)})].join(` · `),children:(0,D.jsxs)(m,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,r.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===u),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((r.score+.5)/c*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(i,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(r.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,c]=(0,E.useState)(null);if(!a)return null;let u=h(t),d=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),f=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(s,{content:f,children:(0,D.jsx)(w,{label:f,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(c)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(d),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(u.width)}%`,height:`${String(u.height)}%`,left:`${String(u.left)}%`,top:`${String(u.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(C,{isOpen:o!==null,onOpenChange:e=>{e||c(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:i,detail:a}){let s=l(),c=`${e.id} · ${s(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=s(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:a,aside:i?(0,D.jsx)(p,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(r,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{i(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:r,tokens:a,children:o}){let s=l(),c=A();return(0,D.jsx)(S,{children:(0,D.jsxs)(m,{gap:3,style:{opacity:r?.5:1,transition:`opacity ${O}`},"aria-busy":r,children:[o,(0,D.jsx)(T,{children:(0,D.jsx)(i,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,c.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(T,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),l=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let l=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-l,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,c(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:l,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-C9dlIB4I.js";import{t as i}from"./Text-DfN1tSUL.js";import{b as a,w as o}from"./browser-transport-DVnbvtNO.js";import{t as s}from"./Tooltip-BO0yrDVt.js";import{d as c}from"./reader-DhyhAoss.js";import{n as l,o as u}from"./labels-provider-Bv9WPagB.js";import{t as d}from"./useLocale-DtI8SMic.js";import{t as f}from"./HStack-D3i0gAme.js";import{t as p}from"./IconButton-Crxt9XEq.js";import{t as m}from"./VStack-BGVV0uKl.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-CYYtfWNI.js";import{c as y,i as b}from"./trace-patterns-YZSpKAfw.js";import{n as x}from"./studio-console-71u2GwPw.js";import{L as S,R as C,at as w,ct as T}from"./index-C1WNmgOO.js";var E=e(t(),1),D=n(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:r}){let a=l(),o=A(),s=Object.entries(r.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:r.choice,note:a(`@theorem.decision.confidence`,{percent:o.percent.format(r.confidence)}),children:(0,D.jsx)(m,{gap:2,role:`list`,children:s.map(([e,t])=>(0,D.jsxs)(m,{gap:1,role:`listitem`,"aria-label":a(`@theorem.decision.option`,{label:e,percent:o.percent.format(t)}),children:[(0,D.jsxs)(f,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(i,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(i,{type:`supporting`,hasTabularNumbers:!0,children:o.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===r.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:r,labels:a}){let o=l(),s=A(),c=a.length,u=Math.min(c-1,Math.max(0,Math.round(r.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[u]===void 0?s.decimal.format(r.score):F(a[u]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(r.score),max:s.decimal.format(c-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(r.confidence)})].join(` · `),children:(0,D.jsxs)(m,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,r.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===u),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((r.score+.5)/c*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(i,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(r.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,c]=(0,E.useState)(null);if(!a)return null;let u=h(t),d=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),f=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(s,{content:f,children:(0,D.jsx)(T,{label:f,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(c)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(d),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(u.width)}%`,height:`${String(u.height)}%`,left:`${String(u.left)}%`,top:`${String(u.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(w,{isOpen:o!==null,onOpenChange:e=>{e||c(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:i,detail:a}){let s=l(),c=`${e.id} · ${s(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=s(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:a,aside:i?(0,D.jsx)(p,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(r,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{i(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:r,tokens:a,children:o}){let s=l(),c=A();return(0,D.jsx)(C,{children:(0,D.jsxs)(m,{gap:3,style:{opacity:r?.5:1,transition:`opacity ${O}`},"aria-busy":r,children:[o,(0,D.jsx)(S,{children:(0,D.jsx)(i,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,c.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(S,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),l=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let l=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-l,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,c(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:l,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};