@theoremjs/studio 0.3.4-next.855.gc82d4ec → 0.3.4-next.869.gb64db05

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 (206) hide show
  1. package/README.md +1 -1
  2. package/browser-connection.d.ts +12 -0
  3. package/draft.d.ts +26 -2
  4. package/map.d.ts +13 -0
  5. package/map.js +28 -0
  6. package/mod.d.ts +1 -1
  7. package/mod.js +1 -1
  8. package/package.json +5 -5
  9. package/page/assets/Badge-C0KjAK5l.js +1 -0
  10. package/page/assets/BaseTypeahead-BM3FoulY.js +1 -0
  11. package/page/assets/BottomSheet-Bdz8RqsO.js +1 -0
  12. package/page/assets/Button-Cb-mh6ml.js +1 -0
  13. package/page/assets/{Card-DKuxiCN0.js → Card-BUIbjVIe.js} +1 -1
  14. package/page/assets/{Center-C9ai7fq_.js → Center-BVnAO8rr.js} +1 -1
  15. package/page/assets/{CheckboxIndicator-Cca43Ctu.js → CheckboxIndicator-CWc5B_d1.js} +2 -2
  16. package/page/assets/CheckboxInput-BrhD5W3u.js +2 -0
  17. package/page/assets/CodeBlock-B8SfIXyW.js +3 -0
  18. package/page/assets/{CollapsibleGroup-D_hnA9UR.js → CollapsibleGroup-BnWI_jMR.js} +1 -1
  19. package/page/assets/ConsoleFrame-prQmvBQJ.js +3 -0
  20. package/page/assets/DateInput-C-NBD2Av.js +1 -0
  21. package/page/assets/Dialog-BatAn-DX.js +1 -0
  22. package/page/assets/EmptyState-B_rMeBCn.js +1 -0
  23. package/page/assets/Field-BSCYng6A.js +1 -0
  24. package/page/assets/FieldStatus-D_97agai.js +1 -0
  25. package/page/assets/{HStack-CqE4exX9.js → HStack-D3i0gAme.js} +1 -1
  26. package/page/assets/HoverCard-YEWLJPhx.js +1 -0
  27. package/page/assets/Icon-C9dlIB4I.js +48 -0
  28. package/page/assets/{IconButton-Jbcy-K-d.js → IconButton-Crxt9XEq.js} +1 -1
  29. package/page/assets/{ItemSwipeLayer-Vrel9VQX.js → ItemSwipeLayer-CVeHWmee.js} +1 -1
  30. package/page/assets/LayoutContent-NlcSjVn7.js +1 -0
  31. package/page/assets/ListItem-C80mhugw.js +1 -0
  32. package/page/assets/{MenuBottomSheet-BCqfbf6e.js → MenuBottomSheet-BAKdx1Jc.js} +1 -1
  33. package/page/assets/{MenuBottomSheetActionList-4BzDY0Sv.js → MenuBottomSheetActionList-BkRKLMkR.js} +1 -1
  34. package/page/assets/OverflowList-T3oyz0uY.js +1 -0
  35. package/page/assets/PanelSearchInput-CGk0XlVX.js +1 -0
  36. package/page/assets/SchemaFields-B8ZoCrBk.js +1 -0
  37. package/page/assets/ScrollableArea-Db8BBKVt.js +1 -0
  38. package/page/assets/SegmentedControlItem-CTVJbfcv.js +1 -0
  39. package/page/assets/SidePanel-7cMNIHsg.js +2 -0
  40. package/page/assets/Spinner-sCbvL2qs.js +1 -0
  41. package/page/assets/{Stack-De5MY0tq.js → Stack-BZiu21ta.js} +1 -1
  42. package/page/assets/Text-DfN1tSUL.js +2 -0
  43. package/page/assets/TextInput-CYSGEp-G.js +1 -0
  44. package/page/assets/{TimestampHoverCard-Lt3iYlao.js → TimestampHoverCard-0-rfsRpo.js} +1 -1
  45. package/page/assets/Token-C0MCeuZZ.js +1 -0
  46. package/page/assets/TokenizerBottomSheet-DgHHQbMZ.js +1 -0
  47. package/page/assets/{ToolResultCharts-DR8osutJ.js → ToolResultCharts-8Z8PG65Q.js} +1 -1
  48. package/page/assets/{Toolbar-BKXtT7K9.js → Toolbar-CH-nc1zH.js} +1 -1
  49. package/page/assets/Tooltip-BO0yrDVt.js +1 -0
  50. package/page/assets/TraceInspector-BlLVhWaD.js +1 -0
  51. package/page/assets/TraceOverview-DGIAvCW_.js +57 -0
  52. package/page/assets/{VStack-CCYGIv4A.js → VStack-BGVV0uKl.js} +1 -1
  53. package/page/assets/{_virtual_studio-type-sources-DW2xrHRZ.js → _virtual_studio-type-sources-NQ8eY2_H.js} +1470 -320
  54. package/page/assets/browser-connection-Nwupg4Oq.js +1 -0
  55. package/page/assets/browser-engine-CLCjrxrC.js +16 -0
  56. package/page/assets/browser-transport-Bv6Cau54.js +2 -0
  57. package/page/assets/browserClickWait-F6QvgsDI.js +1 -0
  58. package/page/assets/compile-Brpb8u3_.js +2 -0
  59. package/page/assets/{layerScopedContext-BA4VBuWG.js → devWarning-B-QAZEJI.js} +1 -1
  60. package/page/assets/{embedding-space-view-CRxJE7jA.js → embedding-space-view-D-Bnd0fH.js} +1 -1
  61. package/page/assets/{encode-files-JlTZOKQT.js → encode-files-CQ_E7QUG.js} +1 -1
  62. package/page/assets/{export-agent-TUBILmVw.js → export-agent-Cmvo5grj.js} +3 -3
  63. package/page/assets/fieldParts-DJZ7Rxcc.js +1 -0
  64. package/page/assets/{focusReturn-DF3Bi_HC.js → focusReturn-C7gRi2IE.js} +1 -1
  65. package/page/assets/{guardrail-tester-C2ahl2Sm.js → guardrail-tester-BrxgKLMf.js} +2 -2
  66. package/page/assets/highlightStyles-C7fXGwpK.js +50 -0
  67. package/page/assets/index-B9sy5r24.js +150 -0
  68. package/page/assets/inputStyles.stylex-CwhFgCYO.js +1 -0
  69. package/page/assets/isApplePlatform-BSwFAKoe.js +1 -0
  70. package/page/assets/json-code-BjPSAV7R.js +3 -0
  71. package/page/assets/{labels-provider-W8DCgjbB.js → labels-provider-Cdg61Tfx.js} +1 -1
  72. package/page/assets/{live-messages-iGBTap-t.js → live-messages-CDqr92n4.js} +1 -1
  73. package/page/assets/{map-token-_aDyWhNO.js → map-token-CgKWabfH.js} +1 -1
  74. package/page/assets/menuBottomSheet.stylex-DRbZhkuJ.js +1 -0
  75. package/page/assets/prompt-row-6SUZf7NQ.js +75 -0
  76. package/page/assets/{read-map-i9VRmt7r.js → read-map-BJqwz_gJ.js} +1 -1
  77. package/page/assets/reader-CYeq9zud.js +5 -0
  78. package/page/assets/registry-Du0mj5wR.js +1 -0
  79. package/page/assets/{schema-DfEjr_N4.js → schema-Cra2BPNa.js} +2 -2
  80. package/page/assets/shaped-data-BlRLB3TY.js +25 -0
  81. package/page/assets/sharedMutationObserver-BHa8gqlp.js +1 -0
  82. package/page/assets/{stub-CsZVvwgT.js → stub-J7M8qV3l.js} +1 -1
  83. package/page/assets/{studio-code-pane-Krc6R7c4.js → studio-code-pane-T1G5_SXQ.js} +4 -4
  84. package/page/assets/{studio-console-Cdmx1jE7.js → studio-console-Dhjgp9m8.js} +1 -1
  85. package/page/assets/{studio-decision-SUjLe9LY.js → studio-decision-BvTPixPE.js} +1 -1
  86. package/page/assets/studio-embedding-CI1qYy8H.js +2 -0
  87. package/page/assets/studio-host-console-BOR62HKM.js +2 -0
  88. package/page/assets/studio-labels-2O090qBe.js +3 -0
  89. package/page/assets/{studio-live-DVVhjsUt.js → studio-live-PavFV9rI.js} +3 -3
  90. package/page/assets/studio-map-zWaeNeKY.js +1 -0
  91. package/page/assets/{studio-trace-replay-3BPGonrL.js → studio-trace-replay-DjJvbdOo.js} +3 -3
  92. package/page/assets/{studio-type-checker-dXJ4DZVL.js → studio-type-checker-DDcpR_0b.js} +1 -1
  93. package/page/assets/{InputClearButton-ClwCL3dr.js → textEntryTraits-C8qoTZ3W.js} +1 -1
  94. package/page/assets/tool-schema-DWmQkthX.js +13 -0
  95. package/page/assets/{trace-patterns-DFMwRU00.js → trace-patterns-YZSpKAfw.js} +1 -1
  96. package/page/assets/trace-record-C07Cf_EG.js +1 -0
  97. package/page/assets/tree-CgaAoXtn.js +3 -0
  98. package/page/assets/{turn-client-CobwqNwm.js → turn-client-B4zazitl.js} +2 -2
  99. package/page/assets/{types-2sRz_M-W.js → types-D5agZBnA.js} +1 -1
  100. package/page/assets/{use-one-call-Cp4nCdQC.js → use-one-call-BgGMm9MZ.js} +1 -1
  101. package/page/assets/use-second-ticker-C09v74b0.css +1 -0
  102. package/page/assets/useAnnounceRenderedText-BWNmfFlE.js +1 -0
  103. package/page/assets/useBusyAnnouncement-DwJYqyJC.js +1 -0
  104. package/page/assets/useClipboard-C7IeReFJ.js +1 -0
  105. package/page/assets/useFocusLeavingChange-8rK2N7Tp.js +1 -0
  106. package/page/assets/useHighlightedOptionScroll-Do3FP80C.js +1 -0
  107. package/page/assets/useIsHydrating-wiKgLSH8.js +1 -0
  108. package/page/assets/useKeyboardHint-B6oH_Cll.js +1 -0
  109. package/page/assets/useLayerDismissal-CqRa7y6J.js +1 -0
  110. package/page/assets/useLocale-DtI8SMic.js +1 -0
  111. package/page/assets/useMediaQuery-Dvkq1PZg.js +1 -0
  112. package/page/assets/useMenuOverflow-x8Ox3IyG.js +1 -0
  113. package/page/assets/useMenuPress-DM12OZUv.js +1 -0
  114. package/page/assets/useMergedRefs-DJD-JnFZ.js +1 -0
  115. package/page/assets/usePressFeedback-nkH67NDc.js +1 -0
  116. package/page/assets/useResolvedRequired-B-0WnbIo.js +1 -0
  117. package/page/assets/useScrollLock--U5R1vFj.js +1 -0
  118. package/page/assets/useScrollableArea-uSlz-RoI.js +1 -0
  119. package/page/assets/{useSettledOpen-DTsZ7A6A.js → useSettledOpen-BJQ5dTsM.js} +1 -1
  120. package/page/assets/useTooltip-NPYEayzZ.js +1 -0
  121. package/page/assets/{useTranslator-Ba7ULSHc.js → useTranslator-CGZ-h6ng.js} +1 -1
  122. package/page/assets/{workspace-C7bvk7HE.js → workspace-Dsqtx6eI.js} +1 -1
  123. package/page/index.html +83 -83
  124. package/types.d.ts +10 -0
  125. package/ui/built/theme.css +2 -2
  126. package/ui/built/theme.css.d.ts +2 -2
  127. package/ui/built/theorem-studio.d.ts +2 -2
  128. package/ui/built/theorem-studio.js +3 -3
  129. package/ui/built/theorem-studio.variants.d.ts +2 -2
  130. package/ui/profile-editor.js +4 -4
  131. package/ui/studio-map.js +4 -13
  132. package/ui/studio-screen.js +20 -7
  133. package/page/assets/Badge-Cj3D81QB.js +0 -1
  134. package/page/assets/BottomSheet-DpTM44kf.js +0 -1
  135. package/page/assets/Button-98PahHB4.js +0 -1
  136. package/page/assets/CheckboxInput-nEEHX5M1.js +0 -2
  137. package/page/assets/CodeBlock-D7u2qG-t.js +0 -3
  138. package/page/assets/ConsoleFrame-DIxyRKED.js +0 -3
  139. package/page/assets/DateInput-C4wSabnj.js +0 -1
  140. package/page/assets/Dialog-C2GP5P7V.js +0 -1
  141. package/page/assets/EmptyState-DVoDGbtj.js +0 -1
  142. package/page/assets/FieldStatus-mbnJ60bK.js +0 -1
  143. package/page/assets/HoverCard-BaUeXNdO.js +0 -1
  144. package/page/assets/Icon-Cluq4EiW.js +0 -48
  145. package/page/assets/LayoutContent-ClBE78rU.js +0 -1
  146. package/page/assets/LayoutFooter-QMRRAZfF.js +0 -1
  147. package/page/assets/ListItem-BevY6nJP.js +0 -1
  148. package/page/assets/OverflowList-CDkPnQmt.js +0 -1
  149. package/page/assets/PanelSearchInput-Dw5TVlEX.js +0 -1
  150. package/page/assets/SchemaFields-DcqZAqsD.js +0 -1
  151. package/page/assets/ScrollableArea-BGmyGfiL.js +0 -1
  152. package/page/assets/SidePanel-CYk_zksv.js +0 -2
  153. package/page/assets/Spinner-B6MdidYQ.js +0 -1
  154. package/page/assets/Text-BDwNaqzZ.js +0 -2
  155. package/page/assets/TextInput-BRBEgg_h.js +0 -1
  156. package/page/assets/Token-BZrQH6-I.js +0 -1
  157. package/page/assets/TokenizerBottomSheet-D9-Y84hI.js +0 -1
  158. package/page/assets/Tooltip-Dhy5lIDA.js +0 -1
  159. package/page/assets/TraceInspector-CTf5pXLc.js +0 -1
  160. package/page/assets/TraceOverview--MUkT_lP.js +0 -57
  161. package/page/assets/browser-connection-CA_G_F8Q.js +0 -1
  162. package/page/assets/browser-engine-DLkf7rll.js +0 -16
  163. package/page/assets/browser-transport-_E7cXrRm.js +0 -2
  164. package/page/assets/compile-CYYqzzo2.js +0 -2
  165. package/page/assets/devWarning-DxuplmRl.js +0 -1
  166. package/page/assets/fieldParts-DOfguMAs.js +0 -1
  167. package/page/assets/highlightRanges-B7TRPq9q.js +0 -51
  168. package/page/assets/index-DNFrrd7f.js +0 -150
  169. package/page/assets/inputStyles.stylex-Dmh4r-B9.js +0 -1
  170. package/page/assets/isRenderable-DHkzpAoQ.js +0 -1
  171. package/page/assets/json-code-6CMWxg9k.js +0 -3
  172. package/page/assets/menuBottomSheet.stylex-BoKs4EdV.js +0 -1
  173. package/page/assets/padding.stylex-BWRTzhFl.js +0 -1
  174. package/page/assets/prompt-row-Dfq6zt8n.js +0 -71
  175. package/page/assets/reader-DhyhAoss.js +0 -5
  176. package/page/assets/registry-CtZn4S17.js +0 -1
  177. package/page/assets/shaped-data-CtJtZSw9.js +0 -21
  178. package/page/assets/studio-embedding-CUtJxKkB.js +0 -2
  179. package/page/assets/studio-host-console-C5kM-YLK.js +0 -2
  180. package/page/assets/studio-labels-CUaktj1R.js +0 -3
  181. package/page/assets/studio-map-DXfBjKcg.js +0 -1
  182. package/page/assets/tool-schema-hDeCZqPI.js +0 -17
  183. package/page/assets/trace-record-C-Opk3HK.js +0 -1
  184. package/page/assets/tree-Bo29WGA0.js +0 -3
  185. package/page/assets/use-second-ticker-D0uA9-ps.css +0 -1
  186. package/page/assets/useAnnounce-QM3mmuiE.js +0 -1
  187. package/page/assets/useAnnounceRenderedText-_-FYc-5m.js +0 -1
  188. package/page/assets/useBusyAnnouncement-CjJI13FX.js +0 -1
  189. package/page/assets/useClipboard-CAtohmvr.js +0 -1
  190. package/page/assets/useDevWarning-WeXt8Pe8.js +0 -1
  191. package/page/assets/useFocusLeavingChange-Bb1WH0Lr.js +0 -1
  192. package/page/assets/useHighlightedOptionScroll-CFs91KPl.js +0 -1
  193. package/page/assets/useIsHydrating-JHu3d-Y0.js +0 -1
  194. package/page/assets/useKeyboardHint-BP66YM6d.js +0 -1
  195. package/page/assets/useLayerDismissal-7g2rAKDN.js +0 -1
  196. package/page/assets/useLocale-d7ARRGFj.js +0 -1
  197. package/page/assets/useMediaQuery-D0tQ79Tl.js +0 -1
  198. package/page/assets/useMenuOverflow-nA_EuFZP.js +0 -1
  199. package/page/assets/useMenuPress-BHmqa9bx.js +0 -1
  200. package/page/assets/useMergedRefs-BgzyWuff.js +0 -1
  201. package/page/assets/usePressFeedback-BpX4yZ5R.js +0 -1
  202. package/page/assets/useResolvedRequired-DR7Agwbm.js +0 -1
  203. package/page/assets/useScrollLock-Dm92sJDr.js +0 -1
  204. package/page/assets/useScrollableArea-CIrHdx_f.js +0 -1
  205. package/page/assets/useTooltip-ClCeZiOV.js +0 -1
  206. /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-Bv6Cau54.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 ee,t as te}from"./studio-labels-2O090qBe.js";import{t as E}from"./IconMicrophone-BT77cilC.js";import{Ja as D,Na as O,fa as k,pa as A}from"./shaped-data-BlRLB3TY.js";import{c as j}from"./host-patterns-F-KZIzkF.js";import{S as M,g as N,r as P,t as F}from"./reader-CYeq9zud.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as ne,y as re}from"./turn-client-B4zazitl.js";import{r as ie,t as ae}from"./live-messages-CDqr92n4.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-Cdg61Tfx.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-CH-nc1zH.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-B9sy5r24.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 j(`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 j(`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 j(`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 j(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new j(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new j(`network`,`live socket error`))}}catch(e){this.failOpen(new j(`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 j(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=A(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 j(`request`,`live session is not connected`);let n=ae.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new j(`request`,D(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new j(`request`,D(`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=k(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 j(`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,ee]=(0,Z.useState)([]),[te,E]=(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&&E(!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:ee,everConnected:te,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 j(`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 j(`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 j(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new j(`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)(ee,{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:E}),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:te,call:n,trace:e})}export{Jt as ProjectLive,qt as StudioLive};
@@ -0,0 +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-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-CgaAoXtn.js";import{F as x,i as S}from"./workspace-Dsqtx6eI.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-B9sy5r24.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 K(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))}}function ne(e,t){let n=new Set([t]),r=new Set,i=(i,a)=>{let o=new Set,s=[t];for(let t=s.pop();t!==void 0;t=s.pop())for(let c of e)(c[i]===t||c.link[i]===t)&&(r.add(c.link),n.add(c.link.from).add(c.link.to).add(c.from).add(c.to),!o.has(c[a])&&(o.add(c[a]),s.push(c[a])))};return i(`to`,`from`),i(`from`,`to`),{ids:n,lines:r}}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 ae(e){return e.kind===`tool`||e.kind===`shared`?2:1}var oe=24,q=8,J=16;function se(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 ce(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||ae(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(se(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)/oe)).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),le={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${O}.map`:`${O}.map.project:${e}`;function ue(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 de(e){try{let t=JSON.parse(k()?.getItem(X(e))??`null`);return D(t)?{tokens:ue(t.tokens),detail:ue(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:le}catch{return le}}function fe(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 pe(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 me(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 he=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function ge(e,t){let n=0,r=120,i=()=>{--r;let a=pe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=he(e.left,a.scrollWidth-a.clientWidth),r=he(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 _e=e=>e.button===0&&e.pointerType!==`touch`;function ve(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 ye(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!_e(t)||t.target.closest(e))return;let r=pe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),ve(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),be={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},xe={...be,node:{width:240,height:84}},Se=28;function Ce(e){return e.length>Se?`${e.slice(0,27)}…`:e}function we({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 Te(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 Ee=4,De=24,Oe={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function ke(e){let t=N()?.name,[n,r]=(0,Y.useState)(()=>de(t)),i=e=>{r(e),fe(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:K(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 Ae(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||!_e(o))return;let c;ve(o,(e,r)=>{!c&&Math.hypot(e,r)<Ee||(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?Oe[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*De,0),c=Math.max(o.y+a.y*De,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function je(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{if(t===void 0)return[new Set,new Set];let{ids:n,lines:r}=ne(e.lines,t);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 Me(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 ge(n,e=>{let{left:t,top:r}=me(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 Ne(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 Pe({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 Fe(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:Ce(t.long??t.label),icon:we(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>Se?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Ie(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:we(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:ae(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:Te(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 Le({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}=ke((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:K(u,y),[u,h,y]),x=h.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),C=s?xe:be,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=w(S,T),D=(0,Y.useMemo)(()=>ce(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;Me(S,l,{place:k===void 0?void 0:D.nodes[k],sizes:C});let{dragging:A,draggable:j}=Ae(D,d,f),{panning:M,pan:N}=ye(`[data-map-node]`),{lit:P,on:I,onLines:L,lights:R}=je(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=Ne(O.find(e=>e.id===B),i,z),W=s?Ie:Fe,G=e=>L.has(e.link)?2:+(e.from===k||e.to===k),ne=[...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:ne.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)(Pe,{actions:z,query:h,onQuery:v,onClose:o})]})}export{Le as StudioMap};
@@ -1,3 +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-Cluq4EiW.js";import{a}from"./fieldParts-DOfguMAs.js";import{t as o}from"./Text-BDwNaqzZ.js";import{t as s}from"./Button-98PahHB4.js";import{_ as c,a as l,f as u,g as d,o as f,p,s as m}from"./browser-transport-_E7cXrRm.js";import{i as h,r as g}from"./row-keys-0Bn7ZyYy.js";import{g as _,t as v}from"./studio-labels-CUaktj1R.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-W8DCgjbB.js";import{t as D}from"./HStack-CqE4exX9.js";import{t as O}from"./IconButton-Jbcy-K-d.js";import{t as k}from"./VStack-CCYGIv4A.js";import{a as A,i as j,o as M,t as N}from"./ConsoleFrame-DIxyRKED.js";import{D as P,E as ee,F as te,H as ne,L as re,N as ie,P as ae,Xt as oe,l as se,o as F,vt as ce,yt as le}from"./index-DNFrrd7f.js";var I=e=>typeof e==`object`&&!!e&&!Array.isArray(e),L=(e,t)=>e.attributes[t],R=(e,t)=>{let n=L(e,t);return typeof n==`string`?n:void 0};function z(e,t,n){let r=L(t,n);return r===void 0?void 0:S(e,r)}function B(e,t,n){let r=z(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function V(e,t,n){let r=z(e,t,n);return Array.isArray(r)?r.filter(I):[]}var H=e=>Array.isArray(e.parts)?e.parts.filter(I):[],U=e=>BigInt(String(e.startTimeUnixNano)),W=(e,t)=>{let n=U(e)-U(t);return n===0n?0:n<0n?-1:1};function G(e){let t=e.endTimeUnixNano;if(!t)return;let n=U(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 ue(e){let t=G(e);if(t)return{workedMs:t.endedAt-t.startedAt,endedAt:t.endedAt}}function de(e,t){let n=ue(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 fe=e=>`content_sha256`in e||`json_sha256`in e;function K(e){let t=e.arguments;if(I(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return I(e)?e:{}}catch{return{}}}function q(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 pe(e){let t=[],n=[],r=!1;for(let i of e){let e=H(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=q(i);fe(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:K(i)}})):(i.type===`blob`||i.type===`uri`)&&(r=!0)}}return{events:t,calls:n,missing:r}}function me(e,t){for(let n=e;n;n=t.get(n.parentSpanId??``)){let e=R(n,`gen_ai.agent.name`);if(R(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var J=e=>R(e,`gen_ai.operation.name`);function he(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>J(e)===`chat`).toSorted(W).map(n=>{let r=pe(V(e,n,`gen_ai.output.messages`)),i=R(n,`theorem.stop.kind`)??`completed`;return{agent:me(n,t),...r,events:[...r.events,{type:`done`,stop:{kind:i}}]}})}function ge(e){return e.spans.filter(e=>J(e)===`execute_tool`).toSorted(W).map(t=>({name:R(t,`gen_ai.tool.name`)??``,result:B(e,t,`gen_ai.tool.call.result`),failed:R(t,`theorem.tool.outcome`)===`error`}))}function _e(e,t){let n=V(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?H(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)I(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=R(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=>J(e)===`execute_tool`).toSorted(W),r=new Set,i=(e,t)=>{let i=n.find(t=>R(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&R(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of V(e,t,`gen_ai.output.messages`))for(let t of H(n)){let n=q(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,K(t),i))}}let o=B(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=R(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=G(a),c=s?.startedAt??Number(U(a)/1000000n),l=s?.endedAt??c,u=B(e,a,`gen_ai.tool.call.result`),d=R(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:R(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?z(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=_e(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||J(a)!==`invoke_agent`||we(e,a))return;let o=he(e),s=ge(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=R(a,`gen_ai.agent.name`)??``,u=R(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(U(a)/1000000n)},t.set(d,f));let p=_e(e,a),m={...p,calls:o,results:s,blocks:de(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 I(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=I(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:F(),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=ie(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)(te,{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)(ne,{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:oe,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)(ae,{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=le(),{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:F(),traces:y}),[e,x,s,y]),C=(0,Y.useMemo)(()=>s?_(e):void 0,[s,e]),w=ee({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
+ 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-Bv6Cau54.js";import{i as h,r as g}from"./row-keys-0Bn7ZyYy.js";import{g as _,t as v}from"./studio-labels-2O090qBe.js";import{t as y}from"./IconHistory-DdcWdeRG.js";import{nn as b}from"./shaped-data-BlRLB3TY.js";import{c as x}from"./host-patterns-F-KZIzkF.js";import{n as S}from"./trace-record-C07Cf_EG.js";import{n as C}from"./trace-schema--4IGmLeE.js";import{v as w}from"./turn-client-B4zazitl.js";import{n as T,t as E}from"./labels-provider-Cdg61Tfx.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-prQmvBQJ.js";import{A as ee,B as te,C as ne,F as re,M as ie,_t as ae,a as P,c as oe,gt as se,j as ce,qt as le,w as F}from"./index-B9sy5r24.js";var I=e=>typeof e==`object`&&!!e&&!Array.isArray(e),L=(e,t)=>e.attributes[t],R=(e,t)=>{let n=L(e,t);return typeof n==`string`?n:void 0};function z(e,t,n){let r=L(t,n);return r===void 0?void 0:S(e,r)}function B(e,t,n){let r=z(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function V(e,t,n){let r=z(e,t,n);return Array.isArray(r)?r.filter(I):[]}var H=e=>Array.isArray(e.parts)?e.parts.filter(I):[],U=e=>BigInt(String(e.startTimeUnixNano)),W=(e,t)=>{let n=U(e)-U(t);return n===0n?0:n<0n?-1:1};function G(e){let t=e.endTimeUnixNano;if(!t)return;let n=U(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 ue(e){let t=G(e);if(t)return{workedMs:t.endedAt-t.startedAt,endedAt:t.endedAt}}function de(e,t){let n=ue(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 fe=e=>`content_sha256`in e||`json_sha256`in e;function K(e){let t=e.arguments;if(I(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return I(e)?e:{}}catch{return{}}}function q(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 pe(e){let t=[],n=[],r=!1;for(let i of e){let e=H(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=q(i);fe(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:K(i)}})):(i.type===`blob`||i.type===`uri`)&&(r=!0)}}return{events:t,calls:n,missing:r}}function me(e,t){for(let n=e;n;n=t.get(n.parentSpanId??``)){let e=R(n,`gen_ai.agent.name`);if(R(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var J=e=>R(e,`gen_ai.operation.name`);function he(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>J(e)===`chat`).toSorted(W).map(n=>{let r=pe(V(e,n,`gen_ai.output.messages`)),i=R(n,`theorem.stop.kind`)??`completed`;return{agent:me(n,t),...r,events:[...r.events,{type:`done`,stop:{kind:i}}]}})}function ge(e){return e.spans.filter(e=>J(e)===`execute_tool`).toSorted(W).map(t=>({name:R(t,`gen_ai.tool.name`)??``,result:B(e,t,`gen_ai.tool.call.result`),failed:R(t,`theorem.tool.outcome`)===`error`}))}function _e(e,t){let n=V(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?H(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)I(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=R(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=>J(e)===`execute_tool`).toSorted(W),r=new Set,i=(e,t)=>{let i=n.find(t=>R(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&R(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of V(e,t,`gen_ai.output.messages`))for(let t of H(n)){let n=q(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,K(t),i))}}let o=B(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=R(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=G(a),c=s?.startedAt??Number(U(a)/1000000n),l=s?.endedAt??c,u=B(e,a,`gen_ai.tool.call.result`),d=R(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:R(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?z(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=_e(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=b(e);if(!a||J(a)!==`invoke_agent`||we(e,a))return;let o=he(e),s=ge(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=R(a,`gen_ai.agent.name`)??``,u=R(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(U(a)/1000000n)},t.set(d,f));let p=_e(e,a),m={...p,calls:o,results:s,blocks:de(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 I(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 x(`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 x(`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=I(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 x(`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 x)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 x(`request`,`This file is not JSON.`);return t.map(({line:e,at:t})=>{let n;try{n=JSON.parse(e)}catch{throw new x(`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:P(),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)(F,{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:le,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)(F,{status:`info`,title:`Recorded with ${t.agent}; a replay runs through ${n.profile.id}.`}):null,s===0?(0,X.jsx)(F,{status:`info`,title:`This trace holds no conversation to replay.`}):null,(0,X.jsx)(ce,{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)(F,{status:`info`,title:`Replaying ${Z(e.turn)} of ${String(t)}`});case`waiting`:return(0,X.jsx)(F,{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)(F,{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)(F,{status:`warning`,title:`Replay stopped at ${Z(t.turn)}, ${n}`,description:t.reason,endContent:l(t.turn)})}case`stopped`:return(0,X.jsx)(F,{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)(F,{status:`error`,title:`Replay stopped at ${Z(e.turn)}`,description:e.message,endContent:l(e.turn)});case`done`:return(0,X.jsx)(F,{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)(F,{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}=oe(),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:P(),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 se(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};
@@ -20,4 +20,4 @@ interface URL {
20
20
  href: string;
21
21
  }
22
22
  declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
23
- `;function n(n,c,l){let u=!1,d=()=>u,f=[],p=e=>(u?e.dispose():f.push(e),e);return m(),{stop(){if(!d()){u=!0;for(let e of f)e.dispose();f.length=0}}};async function m(){let[{default:f},{typeSources:m}]=await Promise.all([e(()=>import(`./studio-ts.worker-BXtW3z-O.js`),[]),e(()=>import(`./_virtual_studio-type-sources-DW2xrHRZ.js`),[])]),h=c.getModel();if(u||!h)return;let g={"lib.host.d.ts":t,...m},_={};for(let[e,t]of Object.entries(g))_[e]={content:t,version:1};let v=p(n.editor.createWebWorker({worker:Promise.resolve(new f).then(e=>(e.postMessage(`ignore`),e.postMessage({compilerOptions:{allowNonTsExtensions:!0,target:7,lib:[`es2022`,`host`],module:99,moduleResolution:100,strict:!0,noEmit:!0,skipLibCheck:!0,allowImportingTsExtensions:!0,paths:{"@theoremjs/agents":[`file:///node_modules/@theoremjs/agents/mod.d.ts`],"@theoremjs/agents/guardrails/compile":[`file:///node_modules/@theoremjs/agents/src/guardrails/compile-egress.d.ts`],zod:[`file:///node_modules/zod/index.d.ts`]}},extraLibs:_,inlayHintsOptions:{}}),e)),keepIdleModels:!0}));if(d())return;let y=()=>v.withSyncedResources([h.uri]),{languages:b}=n;p(b.registerCompletionItemProvider(`typescript`,{triggerCharacters:[`.`],provideCompletionItems:(e,t)=>r(b,y,e,t),resolveCompletionItem:e=>i(b,y,e)})),p(b.registerHoverProvider(`typescript`,{provideHover:(e,t)=>a(y,e,t)})),p(b.registerSignatureHelpProvider(`typescript`,{signatureHelpTriggerCharacters:[`(`,`,`],provideSignatureHelp:(e,t)=>o(y,e,t)})),p(b.registerDefinitionProvider(`typescript`,{provideDefinition:(e,t)=>s(n,g,p,y,e,t)})),!d()&&(c.hasTextFocus()&&c.trigger(`studio`,`editor.action.triggerSuggest`,{}),l())}}async function r(e,t,n,r){try{let i=n.getWordUntilPosition(r),a=n.getOffsetAt(r),o=await(await t()).getCompletionsAtPosition(n.uri.toString(),a);return o?{suggestions:o.entries.map(t=>{let o=t.replacementSpan?l(n,t.replacementSpan):{startLineNumber:r.lineNumber,startColumn:i.startColumn,endLineNumber:r.lineNumber,endColumn:i.endColumn};return{uri:n.uri,position:r,offset:a,label:t.name,insertText:t.name,sortText:t.sortText,kind:p(e,t.kind),range:o,tags:t.kindModifiers?.includes(`deprecated`)===!0?[e.CompletionItemTag.Deprecated]:[]}})}:void 0}catch{return}}async function i(e,t,n){let r=n;if(!r.uri||!r.position||r.offset===void 0)return n;try{let i=await(await t()).getCompletionEntryDetails(r.uri.toString(),r.offset,n.label);return i?{...n,detail:u(i.displayParts),documentation:{value:d(i)},kind:p(e,i.kind)}:n}catch{return n}}async function a(e,t,n){try{let r=await(await e()).getQuickInfoAtPosition(t.uri.toString(),t.getOffsetAt(n));if(!r)return;let i=d(r);return{range:l(t,r.textSpan),contents:[{value:`\`\`\`typescript\n${u(r.displayParts)}\n\`\`\``},...i?[{value:i}]:[]]}}catch{return}}async function o(e,t,n){try{let r=await(await e()).getSignatureHelpItems(t.uri.toString(),t.getOffsetAt(n),{triggerReason:{kind:`invoked`}});return r?{value:{activeSignature:r.selectedItemIndex,activeParameter:r.argumentIndex,signatures:r.items.map(e=>{let t=u(e.prefixDisplayParts),n=e.parameters.map((n,r)=>{let i=u(n.displayParts);return t+=i,r<e.parameters.length-1&&(t+=u(e.separatorDisplayParts)),{label:i,documentation:{value:u(n.documentation)}}});return t+=u(e.suffixDisplayParts),{label:t,parameters:n,documentation:{value:u(e.documentation)}}})},dispose(){}}:void 0}catch{return}}async function s(e,t,n,r,i,a){try{let o=await(await r()).getDefinitionAtPosition(i.uri.toString(),i.getOffsetAt(a));if(!o)return;let s=[];for(let r of o){let i=c(e,t,n,r.fileName);i&&s.push({uri:i.uri,range:l(i,r.textSpan)})}return s}catch{return}}function c(e,t,n,r){let i;try{i=e.Uri.parse(r)}catch{return}let a=e.editor.getModel(i);if(a)return a;if(r in t)return n(e.editor.createModel(t[r],`typescript`,i))}function l(e,t){let n=e.getPositionAt(t.start),r=e.getPositionAt(t.start+t.length);return{startLineNumber:n.lineNumber,startColumn:n.column,endLineNumber:r.lineNumber,endColumn:r.column}}function u(e){return e?.map(e=>e.text).join(``)??``}function d(e){let t=u(e.documentation);for(let n of e.tags??[]){let e=typeof n.text==`string`?n.text:u(n.text);t+=`\n\n*@${n.name}*${e?` — ${e}`:``}`}return t}var f=new Map([[`keyword`,`Keyword`],[`primitive type`,`Keyword`],[`var`,`Variable`],[`local var`,`Variable`],[`const`,`Variable`],[`let`,`Variable`],[`property`,`Field`],[`getter`,`Field`],[`setter`,`Field`],[`function`,`Function`],[`method`,`Function`],[`constructor`,`Function`],[`call`,`Function`],[`construct`,`Function`],[`index`,`Function`],[`enum`,`Enum`],[`module`,`Module`],[`class`,`Class`],[`interface`,`Interface`]]);function p(e,t){return e.CompletionItemKind[f.get(t)??`Property`]}export{n as openTypeChecker};
23
+ `;function n(n,c,l){let u=!1,d=()=>u,f=[],p=e=>(u?e.dispose():f.push(e),e);return m(),{stop(){if(!d()){u=!0;for(let e of f)e.dispose();f.length=0}}};async function m(){let[{default:f},{typeSources:m}]=await Promise.all([e(()=>import(`./studio-ts.worker-BXtW3z-O.js`),[]),e(()=>import(`./_virtual_studio-type-sources-NQ8eY2_H.js`),[])]),h=c.getModel();if(u||!h)return;let g={"lib.host.d.ts":t,...m},_={};for(let[e,t]of Object.entries(g))_[e]={content:t,version:1};let v=p(n.editor.createWebWorker({worker:Promise.resolve(new f).then(e=>(e.postMessage(`ignore`),e.postMessage({compilerOptions:{allowNonTsExtensions:!0,target:7,lib:[`es2022`,`host`],module:99,moduleResolution:100,strict:!0,noEmit:!0,skipLibCheck:!0,allowImportingTsExtensions:!0,paths:{"@theoremjs/agents":[`file:///node_modules/@theoremjs/agents/mod.d.ts`],"@theoremjs/agents/guardrails/compile":[`file:///node_modules/@theoremjs/agents/src/guardrails/compile-egress.d.ts`],zod:[`file:///node_modules/zod/index.d.ts`]}},extraLibs:_,inlayHintsOptions:{}}),e)),keepIdleModels:!0}));if(d())return;let y=()=>v.withSyncedResources([h.uri]),{languages:b}=n;p(b.registerCompletionItemProvider(`typescript`,{triggerCharacters:[`.`],provideCompletionItems:(e,t)=>r(b,y,e,t),resolveCompletionItem:e=>i(b,y,e)})),p(b.registerHoverProvider(`typescript`,{provideHover:(e,t)=>a(y,e,t)})),p(b.registerSignatureHelpProvider(`typescript`,{signatureHelpTriggerCharacters:[`(`,`,`],provideSignatureHelp:(e,t)=>o(y,e,t)})),p(b.registerDefinitionProvider(`typescript`,{provideDefinition:(e,t)=>s(n,g,p,y,e,t)})),!d()&&(c.hasTextFocus()&&c.trigger(`studio`,`editor.action.triggerSuggest`,{}),l())}}async function r(e,t,n,r){try{let i=n.getWordUntilPosition(r),a=n.getOffsetAt(r),o=await(await t()).getCompletionsAtPosition(n.uri.toString(),a);return o?{suggestions:o.entries.map(t=>{let o=t.replacementSpan?l(n,t.replacementSpan):{startLineNumber:r.lineNumber,startColumn:i.startColumn,endLineNumber:r.lineNumber,endColumn:i.endColumn};return{uri:n.uri,position:r,offset:a,label:t.name,insertText:t.name,sortText:t.sortText,kind:p(e,t.kind),range:o,tags:t.kindModifiers?.includes(`deprecated`)===!0?[e.CompletionItemTag.Deprecated]:[]}})}:void 0}catch{return}}async function i(e,t,n){let r=n;if(!r.uri||!r.position||r.offset===void 0)return n;try{let i=await(await t()).getCompletionEntryDetails(r.uri.toString(),r.offset,n.label);return i?{...n,detail:u(i.displayParts),documentation:{value:d(i)},kind:p(e,i.kind)}:n}catch{return n}}async function a(e,t,n){try{let r=await(await e()).getQuickInfoAtPosition(t.uri.toString(),t.getOffsetAt(n));if(!r)return;let i=d(r);return{range:l(t,r.textSpan),contents:[{value:`\`\`\`typescript\n${u(r.displayParts)}\n\`\`\``},...i?[{value:i}]:[]]}}catch{return}}async function o(e,t,n){try{let r=await(await e()).getSignatureHelpItems(t.uri.toString(),t.getOffsetAt(n),{triggerReason:{kind:`invoked`}});return r?{value:{activeSignature:r.selectedItemIndex,activeParameter:r.argumentIndex,signatures:r.items.map(e=>{let t=u(e.prefixDisplayParts),n=e.parameters.map((n,r)=>{let i=u(n.displayParts);return t+=i,r<e.parameters.length-1&&(t+=u(e.separatorDisplayParts)),{label:i,documentation:{value:u(n.documentation)}}});return t+=u(e.suffixDisplayParts),{label:t,parameters:n,documentation:{value:u(e.documentation)}}})},dispose(){}}:void 0}catch{return}}async function s(e,t,n,r,i,a){try{let o=await(await r()).getDefinitionAtPosition(i.uri.toString(),i.getOffsetAt(a));if(!o)return;let s=[];for(let r of o){let i=c(e,t,n,r.fileName);i&&s.push({uri:i.uri,range:l(i,r.textSpan)})}return s}catch{return}}function c(e,t,n,r){let i;try{i=e.Uri.parse(r)}catch{return}let a=e.editor.getModel(i);if(a)return a;if(r in t)return n(e.editor.createModel(t[r],`typescript`,i))}function l(e,t){let n=e.getPositionAt(t.start),r=e.getPositionAt(t.start+t.length);return{startLineNumber:n.lineNumber,startColumn:n.column,endLineNumber:r.lineNumber,endColumn:r.column}}function u(e){return e?.map(e=>e.text).join(``)??``}function d(e){let t=u(e.documentation);for(let n of e.tags??[]){let e=typeof n.text==`string`?n.text:u(n.text);t+=`\n\n*@${n.name}*${e?` — ${e}`:``}`}return t}var f=new Map([[`keyword`,`Keyword`],[`primitive type`,`Keyword`],[`var`,`Variable`],[`local var`,`Variable`],[`const`,`Variable`],[`let`,`Variable`],[`property`,`Field`],[`getter`,`Field`],[`setter`,`Field`],[`function`,`Function`],[`method`,`Function`],[`constructor`,`Function`],[`call`,`Function`],[`construct`,`Function`],[`index`,`Function`],[`enum`,`Enum`],[`module`,`Module`],[`class`,`Class`],[`interface`,`Interface`]]);function p(e,t){return e.CompletionItemKind[f.get(t)??`Property`]}export{n as openTypeChecker};
@@ -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};
@@ -0,0 +1,13 @@
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,F as i,G as a,H as o,I as s,J as c,K as l,L as ee,M as te,N as ne,P as re,Q as ie,R as ae,U as oe,V as se,W as ce,X as le,Y as ue,Z as de,a as u,at as fe,ct as pe,dt as me,et as he,ht as ge,i as d,it as _e,j as ve,lt as ye,mt as f,n as p,nt as be,ot as xe,q as Se,r as m,rt as Ce,st as we,tt as Te,ut as Ee,w as De,z as Oe}from"./schemas-D7cgkv3L.js";import{A as ke,C as Ae,D as je,Gt as Me,Ja as h,Kt as Ne,Rt as Pe,S as Fe,T as Ie,a as Le,c as g,j as Re,k as ze,w as Be}from"./shaped-data-BlRLB3TY.js";var Ve=e({endsWith:()=>ve,gt:()=>te,gte:()=>ne,includes:()=>re,length:()=>Oe,lowercase:()=>r,lt:()=>se,lte:()=>o,maxLength:()=>oe,maxSize:()=>ce,mime:()=>a,minLength:()=>l,minSize:()=>Se,multipleOf:()=>c,negative:()=>ue,nonnegative:()=>le,nonpositive:()=>de,normalize:()=>ie,overwrite:()=>t,positive:()=>he,properties:()=>Te,property:()=>be,regex:()=>Ce,size:()=>_e,slugify:()=>fe,startsWith:()=>xe,toLowerCase:()=>we,toUpperCase:()=>pe,trim:()=>ye,uppercase:()=>Ee}),He=e({ZodISODate:()=>p,ZodISODateTime:()=>m,ZodISODuration:()=>d,ZodISOTime:()=>u,date:()=>We,datetime:()=>Ue,duration:()=>Ke,time:()=>Ge});function Ue(e){return s(m,e)}function We(e){return i(p,e)}function Ge(e){return ae(u,e)}function Ke(e){return ee(d,e)}var _={...De,...Ve,iso:He},qe=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function Je(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function v(e,t){return e.map((e,n)=>n<t?e:e.optional())}function Ye(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Xe(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:Ye(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function Ze(e,t){return _.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function y(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=y(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=y(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Qe=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),$e=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function b(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(b):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Qe.has(e)?b(t):!$e.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(b))}function x(e){return e===1?`element`:`elements`}function et(e,t){return _.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=y(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${x(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${x(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function S(e,t){if(e!==!1)return e===void 0||e===!0?_.any():w(e,t)}var tt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function C(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return _.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return _.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=w(Xe(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return _.null();if(n.length===0)return _.never();if(n.length===1)return _.literal(n[0]);if(n.every(e=>typeof e==`string`))return _.enum(n);let r=n.map(e=>_.literal(e));return r.length<2?r[0]:_.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return _.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>C({...e,type:n},t));return r.length===0?_.never():r.length===1?r[0]:_.union(r)}if(!n)return _.any();let r;switch(n){case`string`:{let t=_.string();if(e.format){let n=e.format;n===`email`?t=t.check(_.email()):n===`uri`||n===`uri-reference`?t=t.check(_.url()):n===`uuid`||n===`guid`?t=t.check(_.uuid()):n===`date-time`?t=t.check(_.iso.datetime({offset:!0})):n===`date`?t=t.check(_.iso.date()):n===`time`?t=t.check(_.regex(tt)):n===`duration`?t=t.check(_.iso.duration()):n===`hostname`?t=t.check(_.hostname()):n===`ipv4`?t=t.check(_.ipv4()):n===`ipv6`?t=t.check(_.ipv6()):n===`mac`?t=t.check(_.mac()):n===`cidr`?t=t.check(_.cidrv4()):n===`cidr-v6`?t=t.check(_.cidrv6()):n===`base64`?t=t.check(_.base64()):n===`base64url`?t=t.check(_.base64url()):n===`e164`?t=t.check(_.e164()):n===`credit_card`?t=t.check(_.creditCard()):n===`iban`?t=t.check(_.iban()):n===`jwt`?t=t.check(_.jwt()):n===`emoji`?t=t.check(_.emoji()):n===`nanoid`?t=t.check(_.nanoid()):n===`cuid`?t=t.check(_.cuid()):n===`cuid2`?t=t.check(_.cuid2()):n===`ulid`?t=t.check(_.ulid()):n===`xid`?t=t.check(_.xid()):n===`ksuid`&&(t=t.check(_.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?_.number().int():_.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=_.boolean();break;case`null`:r=_.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?w(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=w(r,t);f(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=w(i[e],t),r=_.string().regex(new RegExp(e));o.push(_.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(_.object(n).passthrough()),s.push(...o),s.length===0)r=_.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=_.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=_.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!ge(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=_.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=w(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=Ze(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=v(n.map(e=>w(e,t)),a),s=Array.isArray(i)?void 0:S(i,t),c=_.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=v(i.map(e=>w(e,t)),n),o=S(e.additionalItems,t),s=_.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(_.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(_.maxLength(e.maxItems)))}else if(i!==void 0){let n=w(i,t),a=_.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=_.array(_.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=et(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:w(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function w(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n=C(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>w(e,t)),a=_.union(i);n=r?_.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>w(e,t)),a=_.xor(i);n=r?_.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:_.any();else{let i=r?n:w(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=_.intersection(i,w(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=_.nullable(n)),e.readOnly===!0&&(n=_.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!b(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!b(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))qe.has(t)||f(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function nt(e,t){if(typeof e==`boolean`)return e?_.any():_.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:Je(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??me};return w(n,r)}var rt=`https://generativelanguage.googleapis.com/v1beta/models`,it=`Zephyr.Puck.Charon.Kore.Fenrir.Leda.Orus.Aoede.Callirrhoe.Autonoe.Enceladus.Iapetus.Umbriel.Algieba.Despina.Erinome.Algenib.Rasalgethi.Laomedeia.Achernar.Alnilam.Schedar.Gacrux.Pulcherrima.Achird.Zubenelgenubi.Vindemiatrix.Sadachbia.Sadaltager.Sulafat`.split(`.`),at=[`minimal`,`low`,`medium`,`high`],ot=[`pcm`],st=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],ct=[`1K`,`2K`,`4K`],lt=[`image/png`,`image/jpeg`],T=[{type:`builtin`,name:`googleSearch`,description:`Google Search grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`googleMaps`,description:`Google Maps grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`,conflictsWith:[`googleSearch`,`urlContext`]},{type:`builtin`,name:`urlContext`,description:`Fetch URL context`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`codeExecution`,description:`Google code execution`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],ut=[{type:`builtin`,name:`webSearch`,description:`OpenRouter web search`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}],E=`local`;function dt(e,t){return!t&&e===`local`}function D(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var O=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:E,definition:`local`,connection:{baseUrl:D()}},{id:`typesafe`,definition:`typesafe`}],k={gemini:{provider:ze,factory:`geminiProvider`},openrouter:{provider:Ae,factory:`openRouterProvider`},local:{provider:je,factory:`localProvider`},typesafe:{provider:Fe,factory:`typesafeProvider`}};function A(e){return e===void 0?void 0:k[e]?.provider}function ft(){return Object.keys(k)}function pt(e){return Object.keys(k).find(t=>k[t]?.factory===e)}function mt(e){return k[e]?.factory}function j(e,t){return e.find(e=>e.id===t)?.definition}function ht(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function M(e,t,n=A(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,ht(t))}function gt(e){let t=A(e);if(!t)return;if(!t.connection)return[];let r=n(t.connection,{io:`input`});return Object.entries(r.properties??{}).map(([e,t])=>({name:e,required:r.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function _t(e){let t=A(e);return t===void 0||t.key!==void 0}function N(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=A(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Me.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:h(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:h(`protocol.no_key`,{provider:e.id})}),t}function vt(e,t){let n=e.find(e=>e.id===t.provider)??{};return Ne(n,{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function P(e,t){let n=A(e.definition);if(!n)return;let r;try{r=M(Pe(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function F(e,t,n){if(!e)return!1;let r=P(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function yt(e,t,n){if(!bt(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:j(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function bt(e){return[`text`,`image`,`speech`,`transcription`,`live`,`decision`,`embedding`].includes(e)}function xt(e,t){let r=I(n(e.options,{io:`input`,unrepresentable:`any`}),``,!0),i=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return r.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!i.includes(n)||t?.options[n]!==void 0})}function I(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return I(i,a,o);let s={path:a,label:St(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`array`&&i.items?.type===`string`?[{...s,kind:`names`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function St(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Ct(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function L(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?L(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var R=`studio`,wt={"observability.writeTo":R};function Tt(e){return Object.entries(wt).reduce((e,[t,n])=>z(e,t.split(`.`),n),e)}function z(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=z(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var Et=new Set(T.map(e=>e.name));function Dt(e){return e.protocol===Re.id||e.protocol===ke.id}function Ot(e){return e.protocol===Be.id||e.protocol===Ie.id}function kt(e){return Et.has(e)}function At(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):F(t,e)}var jt={text:`fast`,image:`image`,speech:`voice`,transcription:`transcription`,live:`live`,decision:`decision`,embedding:`embedding`};function Mt(e,t){let n=t?.(e)??{...B(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:jt[e],...n}}function B(e,t){let n=O.find(t=>t.id===e),r=n&&P(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Nt(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var Pt=5,Ft=100,It=120;function V(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||g(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Lt(e){return g(e.items)?e.items:void 0}function H(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function U(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function W(e,t){let n=U(e,`minimum`),r=U(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=Ft?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Rt(e){if(e.format===`date`)return{kind:`date`};let t=U(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>It,type:e.format===`email`?`email`:`text`}}function zt(e){let t=Lt(e),n=H(t);if(n)return{kind:`choices`,options:n};let r=t?V(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Bt(e){let t=H(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Pt};switch(V(e)){case`boolean`:return{kind:`switch`};case`number`:return W(e,!1);case`integer`:return W(e,!0);case`string`:return Rt(e);case`array`:return zt(e);case`object`:return g(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function G(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function K(e){let t=g(e.properties)?e.properties:{},n=G(e);return Object.entries(t).flatMap(([e,t])=>g(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Le(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Bt(t)}]:[])}function Vt(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function Ht(e){let t=Vt(e);if(t)return t.value;switch(V(e)){case`number`:case`integer`:return U(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return q(e);case`string`:case`unknown`:return`example`}}function q(e){let t=g(e.properties)?e.properties:{},n=new Set(G(e)),r={};for(let[e,i]of Object.entries(t))g(i)&&(n.has(e)?r[e]=Ht(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function Ut(e){return q(e)}function Wt(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function J(e,t,n=``){return g(t)?K(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?J(e.control.schema,r,i):[]}):[]}var Gt=`{
2
+ "type": "object",
3
+ "properties": {
4
+ "query": { "type": "string" }
5
+ },
6
+ "required": ["query"]
7
+ }`,Kt=`{
8
+ "type": "object",
9
+ "properties": {
10
+ "result": { "type": "string" }
11
+ },
12
+ "required": ["result"]
13
+ }`;function Y(e){let t=X.get(e);return t||(t=nt(e),X.set(e,t)),t}var X=new WeakMap,Z=new Map,qt=1e3;function Q(e){if(e&&typeof e==`object`){for(let t of Object.values(e))Q(t);Object.freeze(e)}return e}function Jt(e){return q(e)}var Yt={"<":`\\u003C`,">":`\\u003E`,"\u2028":`\\u2028`,"\u2029":`\\u2029`};function $(e){return`'${JSON.stringify(e).slice(1,-1).replaceAll(`\\"`,`"`).replaceAll(`'`,`\\'`).replace(/[<>\u2028\u2029]/g,e=>Yt[e]??e)}'`}function Xt(e,t=$){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:t(e)}function Zt(e,t){let n=e.trim();if(!n)return{ok:!1,error:`${t} JSON Schema is required.`};let r=Z.get(n);if(r)return{ok:!0,schema:r};try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))return{ok:!1,error:`${t} JSON Schema must be an object.`};try{Y(e)}catch(e){return{ok:!1,error:`${t} JSON Schema can't be read: ${e.message}.`}}Z.size>=qt&&Z.clear();let r=Q(e);return Z.set(n,r),{ok:!0,schema:r}}catch{return{ok:!1,error:`${t} JSON Schema is not valid JSON.`}}}export{D as A,_t as B,O as C,pt as D,j as E,xt as F,lt as G,rt as H,N as I,it as J,ct as K,M as L,vt as M,dt as N,A as O,Ct as P,P as R,E as S,mt as T,T as U,L as V,st as W,ut as X,at as Y,kt as _,$ as a,At as b,Ut as c,K as d,Wt as f,Ot as g,Dt as h,Zt as i,yt as j,ft as k,J as l,B as m,Kt as n,Jt as o,R as p,ot as q,Xt as r,Y as s,Gt as t,q as u,Nt as v,gt as w,Tt as x,Mt as y,F as z};
@@ -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};
@@ -0,0 +1 @@
1
+ import{$t as e,Hn as t,Jr as n,Un as r,ca as i,da as a,en as o,kr as s,na as c,tn as l,ua as u}from"./shaped-data-BlRLB3TY.js";var d=/^data:([^;,]+);base64,/,f=new Map([[`image`,`data`],[`audio`,`data`],[`thought_signature`,`signature`],[`thought`,`signature`],[`function_call`,`signature`],[`reasoning.encrypted`,`data`]]);function p(e){if(typeof(e.mime_type??e.mimeType)==`string`&&typeof e.data==`string`)return`data`;if(typeof e.media_type==`string`&&typeof e.b64_json==`string`)return`b64_json`;let t=typeof e.type==`string`?f.get(e.type):void 0;return t&&typeof e[t]==`string`&&e[t]!==``?t:void 0}var m=`sha256`,h=`text_sha256`;async function g(e){let t=await a(e);return t?{kind:m,hash:t.hash}:{kind:h,hash:await u(e)}}async function _(e){let t=d.exec(e);if(!t)return e;let{kind:n,hash:r}=await g(e.slice(t[0].length));return`data:${t[1]};${n},${r}`}async function v(e){let t=p(e),n,r=await Promise.all(Object.entries(e).map(async([e,r])=>{if(e===t&&typeof r==`string`){let{kind:t,hash:i}=await g(r);return n=t,[e,i]}return[e,await y(r)]})),i=Object.fromEntries(r);return n&&(i.dataKind=n),i}function y(e){return typeof e==`string`?_(e):Array.isArray(e)?Promise.all(e.map(e=>y(e))):e&&typeof e==`object`?v(e):Promise.resolve(e)}function b(e,t){return t.reduce((e,t)=>s(e,t),e)}function x(e,t){return t.some(Boolean)?i(e,e=>b(e,t)):e}async function S(e,t){return x(await y(e),t)}var C=`https://github.com/open-telemetry/semantic-conventions-genai/tree/8ffdf56`,w=`content_sha256`,T=`json_sha256`,E=[`gen_ai.usage.`,`theorem.usage.`],D={"theorem.upstream.row":`upstreamLog`,"theorem.wire.request":`outboundWire`,"theorem.guardrail":`guardrailDecisions`},O=`raw`,k=`match`,A=[`injection`];function j(e,t){return e===!0||e!==!1&&e[t]}function M(e,{scrub:i,detect:a}){let{sensitive:o,injection:s}=i;return n(e,[...o?r(e,c,o,a):[],...j(o,`host`)?t(e,a):[],...s?r(e,A,s,a):[]])}async function N(e,t){let n=await u(e);return t.content[n]=e,t.known.set(e,n),n}function P(e,t){let{[t]:n,...r}=e;return r}async function F(t,n){if(o(t)){let e=b(M(t.$content,n),n.canaries);return{...P(t,`$content`),[w]:await N(e,n)}}if(e(t)){let e=P(t,`$bytes`),n=await a(t.$bytes);return n?{...e,content_sha256:n.hash,bytes:n.bytes}:{...e,invalid_base64:!0,text_sha256:await u(t.$bytes)}}return l(t)?t:await z(t,e=>F(e,n))}function I(e,t){return typeof e==`string`?t(e):Array.isArray(e)?e.map(e=>I(e,t)):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I(n,t)])):e}function L(e,t){return I(e,e=>{let n=M(e,t),r=t.known.get(n);return r?{[w]:r}:n})}async function R(e,t){if(l(e)){let n=await S(e.$json,t.canaries),r=JSON.stringify(L(n,t)),i=await u(r);return t.content[i]=r,{...P(e,`$json`),[T]:i}}return await z(e,e=>R(e,t))}async function z(e,t){if(Array.isArray(e))return await Promise.all(e.map(t));if(e&&typeof e==`object`){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}return e}async function B(e,t){let n=await Promise.all(Object.entries(e).map(async([e,n])=>[e,await t(n)]));return Object.fromEntries(n)}async function V(e,t){let n=await Promise.all(e.events.map(async e=>({...e,attributes:await B(e.attributes,t)})));return{...e,attributes:await B(e.attributes,t),events:n}}function H(e,t){return t.usage?e:Object.fromEntries(Object.entries(e).filter(([e])=>!E.some(t=>e.startsWith(t))))}function U(e){return e.map(e=>{if(!e||typeof e!=`object`||Array.isArray(e))return e;let{[k]:t,...n}=e;return n})}function W(e,t){let n=D[e.name];if(n&&!t[n])return;if(e.name===`theorem.grounding`&&!t.evidenceRaw){let{[O]:t,...n}=e.attributes;return{...e,attributes:n}}let{hits:r}=e.attributes;return e.name===`theorem.guardrail`&&!t.guardrailMatchPreview&&Array.isArray(r)?{...e,attributes:{...e.attributes,hits:U(r)}}:e}function G(e,t){return{...e,attributes:H(e.attributes,t),events:e.events.flatMap(e=>W(e,t)??[])}}function K(e){return Object.entries(e).flatMap(([e,t])=>t?[e]:[])}async function q(e){let{policy:t}=e,n={scrub:t.scrub,detect:t.detect,canaries:j(t.scrub.canary,`theorem`)?e.canaries??[]:[],content:{},known:new Map},r=e.spans.map(e=>G(e,t.include)),[i]=r;i&&(i.attributes={...i.attributes,"theorem.record.include":K(t.include),"theorem.record.scrub":K(t.scrub)});let a=await Promise.all(r.map(e=>V(e,e=>F(e,n)))),o=await Promise.all(a.map(e=>V(e,e=>R(e,n))));return{v:3,schemaUrl:C,resource:{...t.resource},...e.metadata?{metadata:e.metadata}:{},spans:o,content:n.content}}function J(e,t){if(Array.isArray(t))return t.map(t=>J(e,t));if(!t||typeof t!=`object`)return t;let n=Object.fromEntries(Object.entries(t).map(([t,n])=>[t,J(e,n)])),{[w]:r,[T]:i,...a}=n,o=typeof r==`string`?e.content[r]:void 0;if(o!==void 0)return Object.keys(a).length===0?o:{...a,content:o};let s=typeof i==`string`?e.content[i]:void 0;if(s===void 0)return n;let c=J(e,JSON.parse(s));return Object.keys(a).length===0?c:c&&typeof c==`object`&&!Array.isArray(c)?{...c,...a}:n}export{J as n,q as t};
@@ -0,0 +1,3 @@
1
+ import{C as e,M as t,h as n,j as r,n as i,p as a,t as o,y as s,z as ee}from"./tool-schema-DWmQkthX.js";import{Ai as c,Da as l,Ei as u,Et as d,Hi as te,Nt as ne,Qi as re,Ri as ie,Vi as f,Xi as ae,_n as oe,fn as p,hi as se,ja as m,ki as h,xi as g}from"./shaped-data-BlRLB3TY.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:ie,inputs:f(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??f(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(n=>n.provider!==`local`&&!t(e.providers,n).keySlot)}function b(e,n){let r={provider:n.provider,keySlot:n.keySlot||e.models.key,fallbackKeySlot:n.fallbackKeySlot||e.models.fallbackKey},i=t(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var x=g,S=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],C=2147483647,w={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},T={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function E(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function D(e){return{key:E(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var O=`Studio stub tool — returns a fixed result.`;function k(e){return{key:E(`tool`),toolName:`my_tool`,toolType:`function`,description:O,category:`studio`,access:u[0],permission:c[0],loadTier:h[0],paths:[`*`],inputJson:o,outputJson:i,...e}}function A(e,t,n){return(!e.description.trim()||e.description===O)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function j(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function M(){return{key:``,label:``,at:m(l,()=>`ignore`),patterns:[j()],hint:``}}function N(){let e=oe(void 0);return{canaryBindNote:``,detect:m(te,t=>({...e.detect[t]})),sources:Object.fromEntries(ae.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function P(){let e=_({});return{writeTo:a,destination:a,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function F(e){return e.map(([e,t])=>({key:E(`criterion`),label:e,text:t}))}function I(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:E(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:F([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:E(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:F([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var L=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),R=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),ge=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
2
+
3
+ `),_e=`How do I delete every screenshot on my desktop?`;function ve(e,t=`choice`){let n=q(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:E(`question`),id:n,type:t,instructions:``,criteria:B(t)}}function ye(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=q(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:E(`image`),name:i,...n}}function be(){return{key:E(`option`),name:``,label:``,isShownInChat:!1,choices:[]}}function xe(e,t){return e.map(e=>t.find(t=>t.value===e)??{key:E(`choice`),value:e,description:``})}function z(){return{key:E(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:F(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Se(){return{identity:{agentId:``,profileType:``,handle:``,system:``,options:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:ne({type:`text`}),atStepLimit:`stop`},guardrails:N(),observability:P(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:v(`audio`),ingressVideo:v(`video`),ingressText:v(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:I(),labels:{}}}var Ce=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&Ce.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&V(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function U(e,t){let n=e.identity.profileType;return n!==``&&f(t).includes(n)}function we(e,t,n){if((!n||n.includes(t.key))&&t.loadTier===`T2`&&U(e,`tools.t2Loader`)&&!e.tools.t2Loader.trim())return`No T2 loader is set under Tools, so this tool never loads.`}function Te(e){return U(e,`identity.system`)&&re(e.guardrails.detect,`canary_leak`)}function Ee(e){let t=e.identity.profileType;return t!==``&&d.includes(t)}function W(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&V(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function De(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>p(se,e)),voiceAccept:[]}}function Oe(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function ke(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function G(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ae(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:G(e.models.defaultModel,n)},modelBindings:n}}function K(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=s(r,t),o=q(a.modelId,i,e=>`${a.modelId}${e}`);return D({...a,modelId:o})}function je(e){return k({toolName:q(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function q(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Me(e,t,i){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let a=e.modelBindings.filter(n=>{let a=r(e.providers,t,n),o=e.providers.find(e=>e.id===n.provider);return ee(o,t,n.protocol)&&!Fe(i,t,a)}),o={...e,identity:{...e.identity,profileType:t},modelBindings:a},s=a.length?a:[K(o,i?.start)],c=!e.models.key&&fe({...o,modelBindings:s}),l=t===`speech`&&!e.speech.voice.trim()&&s.some(i=>n(r(e.providers,t,i)));return{...o,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,s),key:c?Ie:e.models.key},modelBindings:s}}var Ne=`Kore`,Pe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Fe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&Pe.some(e=>e!==t&&r(e))}var Ie=`slot_a`;function Le(e,t){return W(e).includes(t)?{...e,included:[...e.included,t]}:e}function Re(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function J(e){return`modelBinding:${e}`}var Y=`toolSpec:`;function X(e){return`${Y}${e}`}function Z(e){return e.startsWith(Y)?e.slice(9):void 0}var Q=`provider:`;function ze(e){return`${Q}${e}`}function Be(e){return e.startsWith(Q)?e.slice(9):void 0}var Ve=new Map(y.map(e=>[e.id,e.label]));function He(e){return Ve.get(e)??e}function Ue(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=Z(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=H(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:J(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||`Unnamed model`,children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:X(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=H(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:He(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{B as A,Te as B,H as C,W as D,q as E,be as F,b as G,Me as H,M as I,he as J,me as K,j as L,ye as M,ve as N,Le as O,K as P,je as R,U as S,Re as T,Ee as U,Ae as V,ke as W,y as X,pe as Y,ue as Z,C as _,Ge as a,D as b,$ as c,_e as d,ge as f,x as g,S as h,Ue as i,z as j,we as k,w as l,T as m,Be as n,Z as o,R as p,de as q,ze as r,X as s,J as t,L as u,A as v,E as w,k as x,Se as y,xe as z};