@theoremjs/studio 0.3.4-next.606.g8936f75 → 0.3.4-next.608.gd007c52

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 (36) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{Banner-DjmNbolt.js → Banner-DNuB7lhC.js} +2 -2
  3. package/page/assets/CardWall-Y542bbCc.js +1 -0
  4. package/page/assets/{ConsoleFrame-DA11Fku_.js → ConsoleFrame-DRsXYFYa.js} +3 -3
  5. package/page/assets/{MenuBottomSheet-3zlicLHX.js → MenuBottomSheet-Kdylt_it.js} +1 -1
  6. package/page/assets/SchemaFields-DRS_ztxv.js +1 -0
  7. package/page/assets/ToolResultCharts-BnCESJwG.js +1 -0
  8. package/page/assets/TraceInspector-DLaTSe9y.js +1 -0
  9. package/page/assets/TraceOverview-CksdzH-8.js +57 -0
  10. package/page/assets/{browser-engine-CvJbFjEy.js → browser-engine-U4pbMdOL.js} +2 -2
  11. package/page/assets/{browser-transport-BgmUaqDP.js → browser-transport-LV_FgVKG.js} +3 -3
  12. package/page/assets/{export-agent-C68TpApX.js → export-agent-DzvQf-68.js} +2 -2
  13. package/page/assets/{guardrail-tester-nXXVXNzQ.js → guardrail-tester-B1iBUn55.js} +2 -2
  14. package/page/assets/{index-Dblg49i6.js → index-3PUx0L6S.js} +74 -74
  15. package/page/assets/row-keys-WByP9Hsh.js +1 -0
  16. package/page/assets/{studio-code-pane-9xA06tts.js → studio-code-pane-BdQTxi9f.js} +2 -2
  17. package/page/assets/{studio-console-B517lIZ-.js → studio-console-DxPHEOtQ.js} +1 -1
  18. package/page/assets/{studio-decision-Cf2lbMFz.js → studio-decision-WZ1-fSqO.js} +1 -1
  19. package/page/assets/studio-embedding-nDQVQxGy.js +2 -0
  20. package/page/assets/studio-host-console-C-bBbaMQ.js +2 -0
  21. package/page/assets/{studio-labels-CGR8sQpd.js → studio-labels-7sgmTzU-.js} +1 -1
  22. package/page/assets/{studio-live-iNfxo1P9.js → studio-live-BbaCxmkQ.js} +2 -2
  23. package/page/assets/studio-map-D-hwOlzT.js +1 -0
  24. package/page/assets/{studio-trace-replay-cJ1PXrFw.js → studio-trace-replay-m0JyWXs0.js} +1 -1
  25. package/page/assets/use-one-call-ufJV1bYw.js +1 -0
  26. package/page/index.html +5 -5
  27. package/page/assets/CardWall-CBRLdDZW.js +0 -1
  28. package/page/assets/SchemaFields-CpFY3ebA.js +0 -1
  29. package/page/assets/ToolResultCharts-gTYzrv97.js +0 -1
  30. package/page/assets/TraceInspector-DfCvBkOH.js +0 -1
  31. package/page/assets/TraceOverview-BitZyKPI.js +0 -57
  32. package/page/assets/arrive-DvbqpeRS.js +0 -1
  33. package/page/assets/studio-embedding-BEKBtCKn.js +0 -2
  34. package/page/assets/studio-host-console-TXtb6kyY.js +0 -2
  35. package/page/assets/studio-map-BGq5KDQu.js +0 -1
  36. package/page/assets/use-one-call-C95kZjb_.js +0 -1
@@ -1,5 +1,5 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,l as n,n as r,u as i}from"./themeProps-3IqahpCr.js";import{h as a}from"./tokens.stylex-DkHf0P9C.js";import{c as o,i as s,l as c}from"./SegmentedControlItem-BBGRPrxp.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{A as f,E as p,S as m,g as h,s as g,t as _}from"./browser-transport-BgmUaqDP.js";import{t as v}from"./mergeProps-ptS-gIMz.js";import{l as y}from"./fieldParts-B7DYLgh4.js";import{t as b}from"./Icon-BqkS-pIq.js";import{d as x,f as S,h as C,o as ee,u as w}from"./use-trace-records-B1vrKQmA.js";import{t as T}from"./Text-BOqCfzZC.js";import{a as E,n as D,t as O}from"./labels-provider-Bt3Q2GjB.js";import{a as k,c as A,n as j,t as M}from"./IconButton-DVUFx-8p.js";import{t as N}from"./Dialog-Sd04KQS2.js";import{t as P}from"./createReactComponent-CZwsv6DD.js";import{a as F,i as I,t as L}from"./Banner-DjmNbolt.js";import{t as R}from"./Center-nHS1JSux.js";import{_ as te,g as ne,h as re,m as ie,n as ae,r as oe,t as se}from"./studio-labels-CGR8sQpd.js";import{c as z}from"./host-patterns-F-KZIzkF.js";import{Ir as ce,Sr as B,er as le,tr as ue}from"./shaped-data-C4yaGRz9.js";import{S as V,g as de,r as fe,t as H}from"./reader-D_UCUUJt.js";import{i as U}from"./live-ingress-OuSlQ6q7.js";import{i as pe,v as me}from"./turn-client-CZG4gVtX.js";import{r as he,t as ge}from"./live-messages-DzRBDO3t.js";import"./use-second-ticker-BSCE_-wM.js";import{t as _e}from"./EmptyState-C_uF9Wyj.js";import{H as ve,I as ye,S as be,W as xe,bt as Se,dt as Ce,i as W,kt as we,p as Te,vt as Ee,yt as De}from"./index-Dblg49i6.js";var Oe=P(`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`}]]),ke=P(`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`}]]),Ae=P(`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`}]]),je=P(`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`}]]),Me=P(`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`}]]),Ne=P(`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`}]]),Pe=P(`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 Fe(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 Ie(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Le(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 Re(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)}function ze(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 Be=`mic-capture-processor`;function Ve(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function He(e,t,n=16e3){if(t===n)return Ue(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]=We(i>0?n/i:0),o++,s=t}return a}function Ue(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=We(e[n]??0);return t}function We(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function Ge(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 G(e){return JSON.stringify(e)}function Ke(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var qe=.05,Je=[500,1e3,2e3,4e3,8e3];function K(e){return e instanceof Error?e:new z(`internal`,B(e),{cause:e})}function q(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ye(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function Xe(e){let t=Ee(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Ie({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:qe})}function Ze(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Qe=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 z(`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{slots:e,openMessage:t}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{slots:e}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...t?{host:t}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=Je[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new z(`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 z(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new z(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new z(`network`,`live socket error`))}}catch(e){this.failOpen(new z(`internal`,B(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=ze(e);this.failSession(new z(t?`auth`:`internal`,B(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=He(e,t,16e3),r=ue(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(G({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(De(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),Xe({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(Ve()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Be),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?.(Se(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(()=>this.options.onToolCall(e.name,e.arguments,{callId:e.id,operationId:pe(e)})).catch(e=>{this.options.onError?.(K(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=he(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(K(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(V(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?.(V(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Ke();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`:Re(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Le(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=Ze(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?.(K(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new z(`request`,`live session is not connected`);let n=ge.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new z(`request`,ce(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new z(`request`,ce(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(G(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(K(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=le(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=Ge(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?.(K(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(G({type:`text`,text:e}))}setSlots(e){JSON.stringify(e)!==JSON.stringify(this.options.slots)&&(this.options={...this.options,slots:e},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(G({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(G({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(),q(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,q(this.micWorklet),null),q(this.micSource),this.micSource=null,Ye(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},J=e(i(),1);function $e(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function et(e,t){return t.length===0?e:[...e,[...t]]}function tt(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:nt(e,t):e:t}function nt(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function rt(e){return`${String(Date.now())}-${String(e.turns.length)}`}function it(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:nt(s.text,t)};else{let n=i?.forceNew?t:tt(c,t);o.push({id:rt(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function at(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function ot(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function st(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:ot(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 ct(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!at(t))return e;let n=st(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:rt(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function lt(e){return e.role===`work`?me(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var ut=24;function dt(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ft(e,t){let n=e.trim();return dt(n,t.trim())>=Math.min(n.length,ut)}function pt(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`&&ft(t.text,e.text))})}function mt(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=>pt(e).flatMap(lt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function ht({working:e,interimAgent:t}){return t!==``||e}function gt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function _t(e,t){let n=Object.keys(t??{}).sort().join(`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,l as n,n as r,u as i}from"./themeProps-3IqahpCr.js";import{h as a}from"./tokens.stylex-DkHf0P9C.js";import{c as o,i as s,l as c}from"./SegmentedControlItem-BBGRPrxp.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{A as f,E as p,S as m,g as h,s as g,t as _}from"./browser-transport-LV_FgVKG.js";import{t as v}from"./mergeProps-ptS-gIMz.js";import{l as y}from"./fieldParts-B7DYLgh4.js";import{t as b}from"./Icon-BqkS-pIq.js";import{d as x,f as S,h as C,o as ee,u as w}from"./use-trace-records-B1vrKQmA.js";import{t as T}from"./Text-BOqCfzZC.js";import{a as E,n as D,t as O}from"./labels-provider-Bt3Q2GjB.js";import{a as k,c as A,n as j,t as M}from"./IconButton-DVUFx-8p.js";import{t as N}from"./Dialog-Sd04KQS2.js";import{t as P}from"./createReactComponent-CZwsv6DD.js";import{a as F,i as I,t as L}from"./Banner-DNuB7lhC.js";import{t as R}from"./Center-nHS1JSux.js";import{_ as te,g as ne,h as re,m as ie,n as ae,r as oe,t as se}from"./studio-labels-7sgmTzU-.js";import{c as z}from"./host-patterns-F-KZIzkF.js";import{Ir as ce,Sr as B,er as le,tr as ue}from"./shaped-data-C4yaGRz9.js";import{S as V,g as de,r as fe,t as H}from"./reader-D_UCUUJt.js";import{i as U}from"./live-ingress-OuSlQ6q7.js";import{i as pe,v as me}from"./turn-client-CZG4gVtX.js";import{r as he,t as ge}from"./live-messages-DzRBDO3t.js";import"./use-second-ticker-BSCE_-wM.js";import{t as _e}from"./EmptyState-C_uF9Wyj.js";import{Ct as ve,G as ye,Mt as be,S as xe,St as Se,i as W,mt as Ce,p as we,q as Te,xt as Ee,z as De}from"./index-3PUx0L6S.js";var Oe=P(`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`}]]),ke=P(`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`}]]),Ae=P(`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`}]]),je=P(`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`}]]),Me=P(`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`}]]),Ne=P(`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`}]]),Pe=P(`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 Fe(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 Ie(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Le(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 Re(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)}function ze(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 Be=`mic-capture-processor`;function Ve(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function He(e,t,n=16e3){if(t===n)return Ue(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]=We(i>0?n/i:0),o++,s=t}return a}function Ue(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=We(e[n]??0);return t}function We(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function Ge(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 G(e){return JSON.stringify(e)}function Ke(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var qe=.05,Je=[500,1e3,2e3,4e3,8e3];function K(e){return e instanceof Error?e:new z(`internal`,B(e),{cause:e})}function q(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ye(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function Xe(e){let t=Ee(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Ie({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:qe})}function Ze(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Qe=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 z(`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{slots:e,openMessage:t}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{slots:e}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...t?{host:t}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=Je[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new z(`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 z(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new z(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new z(`network`,`live socket error`))}}catch(e){this.failOpen(new z(`internal`,B(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=ze(e);this.failSession(new z(t?`auth`:`internal`,B(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=He(e,t,16e3),r=ue(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(G({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(Se(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),Xe({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(Ve()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Be),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?.(ve(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(()=>this.options.onToolCall(e.name,e.arguments,{callId:e.id,operationId:pe(e)})).catch(e=>{this.options.onError?.(K(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=he(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(K(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(V(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?.(V(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Ke();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`:Re(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Le(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=Ze(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?.(K(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new z(`request`,`live session is not connected`);let n=ge.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new z(`request`,ce(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new z(`request`,ce(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(G(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(K(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=le(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=Ge(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?.(K(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(G({type:`text`,text:e}))}setSlots(e){JSON.stringify(e)!==JSON.stringify(this.options.slots)&&(this.options={...this.options,slots:e},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(G({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(G({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(),q(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,q(this.micWorklet),null),q(this.micSource),this.micSource=null,Ye(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},J=e(i(),1);function $e(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function et(e,t){return t.length===0?e:[...e,[...t]]}function tt(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:nt(e,t):e:t}function nt(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function rt(e){return`${String(Date.now())}-${String(e.turns.length)}`}function it(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:nt(s.text,t)};else{let n=i?.forceNew?t:tt(c,t);o.push({id:rt(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function at(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function ot(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function st(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:ot(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 ct(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!at(t))return e;let n=st(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:rt(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function lt(e){return e.role===`work`?me(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var ut=24;function dt(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ft(e,t){let n=e.trim();return dt(n,t.trim())>=Math.min(n.length,ut)}function pt(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`&&ft(t.text,e.text))})}function mt(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=>pt(e).flatMap(lt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function ht({working:e,interimAgent:t}){return t!==``||e}function gt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function _t(e,t){let n=Object.keys(t??{}).sort().join(`
2
2
  `),r=e?.join(`
3
3
  `);(0,J.useEffect)(()=>{r!==void 0&&Ce(r?r.split(`
4
4
  `):[],n?n.split(`
5
- `):[])},[r,n])}var vt=.62,yt=400;function bt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function xt(e,t){let n=t?.facingMode??`user`;return bt(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 z(`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`,vt).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,yt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await bt(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 St(e){let t=(0,J.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,J.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,J.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=>it(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,J.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await xt(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,J.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,J.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,J.useCallback)(async()=>{t(),await n()},[n,t])}}function Ct(e){return new de(e.kind,e.error,e.message)}function Y(e){e.gateCallId===void 0&&e.clearActiveTool()}function wt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Y(t):e.phase===`error`?(t.reportFailure(Ct(e.failure)),Y(t)):t.setActiveTool(e.name)}function Tt(e,t){e.type===`done`?(t.clearInterim(),Y(t)):e.type===`tool`&&wt(e.tool,t)}function Et(e){let[t,n]=(0,J.useState)(`disconnected`),[r,i]=(0,J.useState)(null),a=(0,J.useRef)({input:0,output:0}),o=(0,J.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,J.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(!1),[f,m]=(0,J.useState)(null),[h,g]=(0,J.useState)($e),[_,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(``),[C,ee]=(0,J.useState)(!1),[w,T]=(0,J.useState)([]),[E,D]=(0,J.useState)(!1),[O,k]=(0,J.useState)(null),[A,j]=(0,J.useState)(`user`),M=(0,J.useRef)(null),N=(0,J.useRef)(h),P=(0,J.useRef)(c),F=(0,J.useRef)(w),I=(0,J.useRef)(t);return N.current=h,P.current=c,F.current=w,I.current=t,(0,J.useEffect)(()=>{C&&D(!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:m,captions:h,setCaptions:g,failure:_,reportFailure:(0,J.useCallback)(t=>{v(p(t,e))},[e]),clearFailure:(0,J.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,J.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,J.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:ee,sessionPermissions:w,setSessionPermissions:T,everConnected:E,videoPreview:O,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,J.useCallback)(()=>{g($e())},[]),stopVideo:(0,J.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),d(!1)},[])}}function Dt(e){let[t,n]=(0,J.useState)(null),r=(0,J.useRef)(t);r.current=t;let i=(0,J.useRef)(null),a=(0,J.useRef)(null),o=(0,J.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,J.useCallback)(t=>{e.setCaptions(e=>ct(e,t)),Tt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>gt(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:e.setActiveTool})},[e,o]),waitForGateDecision:(0,J.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,J.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,J.useCallback)(()=>{a.current?.(new z(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}async function Ot(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.sessionPermissions,s=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,c=await t({callId:i,operationId:a}),l=new Set;for(;c.status!==`settled`;){if(c.status===`dispatched`){if(l.has(c.grantId))return;l.add(c.grantId);let e=c.grantId,n=c.arguments,r=s?await Promise.resolve().then(()=>s(n,{callId:i,operationId:a})).catch(()=>void 0):void 0;c=await t({callId:i,operationId:a,grantId:e,...r?{output:r.output}:{unanswered:!0}});continue}let{gate:u}=c;if(u.kind===`page`){await t({callId:i,operationId:a,decision:`deny`});return}let d=await e.waitForGateDecision({callId:i,toolName:n,input:u.preparedArguments??r,gate:u});if(d===`withdrawn`)return;let f=te({toolName:n,gate:u,sessionPermissions:o,resolution:d});if(f.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}o=f.sessionPermissions,e.setSessionPermissions(f.sessionPermissions),c=await t({callId:i,decision:`approve`,operationId:a,...f.secret===void 0?{}:{secret:f.secret}})}}function kt(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 At(e,t,n,r){r.setCaptions(r=>it(r,e,t,n?.interim))}async function jt(e,t,n,r,i){r.setActiveTool(e),r.clearFailure();let a=i.current;if(!a)r.reportFailure(new z(`request`,`live tool call with no session client`));else try{await Ot({pageTools:r.pageTools,executeToolOnRelay:e=>a.executeToolOnRelay(e),name:e,toolArgs:t,callId:n.callId,operationId:n.operationId,sessionPermissions:r.sessionPermissionsRef.current,setSessionPermissions:e=>{r.sessionPermissionsRef.current=e,r.setSessionPermissions(e)},waitForGateDecision:r.waitForGateDecision})}catch(e){r.reportFailure(e)}finally{r.gatePromptRef.current||r.setActiveTool(null)}}function Mt(e){let t=(0,J.useRef)(null),n=(0,J.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,J.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Qe({...e,slots:r.slots,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{kt(e,n.current)},onTranscript:(e,t,r)=>{At(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):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)},onToolCall:(e,r,i)=>jt(e,r,i,n.current,t)});return t.current=i,i},[]),clearClient:(0,J.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Nt(e,t,n,r){let[i,a]=(0,J.useState)(!1),[o,s]=(0,J.useState)(!1),c=(0,J.useRef)(!1),l=(0,J.useCallback)(t=>{c.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,J.useEffect)(()=>{n&&c.current&&(c.current=!1,e.handleToggleVideo())},[e,n]);let u=(0,J.useCallback)(()=>{c.current=!1,e.teardownSession(),s(!0)},[e]),[d,f]=(0,J.useState)([]),p=(0,J.useCallback)(async()=>{let n=t.current.turns;f(e=>et(e,n)),s(!1),await e.handleRestart()},[e,t]),m=(0,J.useRef)(e.teardownSession);return m.current=e.teardownSession,(0,J.useEffect)(()=>()=>{m.current()},[]),{callStarted:i,ended:o,pastCalls:d,startCall:l,handleEnd:u,handleRestart:p}}function Pt(e,t,n={}){let r=Et(e.labels),i=Dt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,J.useRef)(t);a.current=t;let o=U(e.live.ingress,`audio`),s=U(e.live.ingress,`video`),c=U(e.live.ingress,`text`),l=(0,J.useMemo)(()=>Fe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,J.useMemo)(m,[]),{clientRef:d,ensureClient:f,clearClient:p}=Mt({slots:n.slots,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,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),h=St({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,ended:_,pastCalls:v,startCall:y,handleEnd:b,handleRestart:x}=Nt(h,r.captionsRef,r.sessionActive,s),S=JSON.stringify(n.context);(0,J.useEffect)(()=>{d.current?.setContext(S===void 0?void 0:JSON.parse(S))},[d,S]);let C=JSON.stringify(n.slots);return(0,J.useEffect)(()=>{d.current?.setSlots(C===void 0?void 0:JSON.parse(C))},[d,C]),_t(e.tools.page,n.pageTools),{handle:e.identity.handle,traces:u,callStarted:g,pastCalls:v,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||_||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:b,startCall:y,handleRestart:x,handleSendText:h.handleSendText,handleToggleMic:h.handleToggleMic,handleFlipCamera:h.handleFlipCamera,handleToggleVideo:h.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var X=t(),Ft={0:`--spacing-0`,.5:`--spacing-0-5`,1:`--spacing-1`,1.5:`--spacing-1-5`,2:`--spacing-2`,3:`--spacing-3`,4:`--spacing-4`,5:`--spacing-5`,6:`--spacing-6`,8:`--spacing-8`,10:`--spacing-10`},Z={baseFlex:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x1qughib`,$$css:!0},baseGrid:{k1xSpc:`xrvj5dj`,kumcoG:`x134kloy`,kGNEyG:`x6s0dn4`,$$css:!0},vertical:{kXwgrk:`xdt5ytf`,kGNEyG:`x1qjc9v5`,$$css:!0},startSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,$$css:!0},centerSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,k7Eaqz:`xeuugli`,$$css:!0},endSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x13a6bvl`,$$css:!0},startOnly:{kUk6DE:`x845mor`,$$css:!0},endOnly:{keTefX:`xvc5jky`,$$css:!0}},It={base:{kAzted:`x1gdqauq`,$$css:!0}},Q={gap:e=>[{kOIVth:e==null?e:`x1pidvrl`,$$css:!0},{"--x-gap":(e=>typeof e==`number`?e+`px`:e??void 0)(e)}],tabIndicatorBottom:e=>[{"--_tab-indicator-bottom":e==null?e:`xbrl7fg`,$$css:!0},{"--x---_tab-indicator-bottom":e??void 0}]},Lt={sm:2,md:2,lg:2},Rt={sm:a[`--spacing-2`],md:a[`--spacing-2`],lg:a[`--spacing-2`]},$={sm:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,md:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,lg:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`};function zt({startContent:e,centerContent:t,endContent:i,label:o,size:c=`md`,gap:l=1,orientation:u=`horizontal`,variant:d=`transparent`,dividers:f,xstyle:p,className:m,style:h,ref:g,onKeyDown:_,onFocus:b,onBlur:x,role:S,"aria-label":C,"aria-orientation":ee,...w}){let T=t!=null,E=e!=null,D=i!=null,O=f?.includes(`bottom`)??!1,j=a[Ft[l]],{listRef:M,handleKeyDown:N,handleFocus:P}=y({itemSelector:`button, input, [tabindex]`,boundarySelector:`[role="toolbar"], [popover]`,orientation:u,hasRovingTabIndex:!0,hasCaretGuard:!0}),{hintElement:F,onKeyDown:I,onFocus:L,onBlur:R}=s({orientation:u}),te=(0,J.useCallback)(e=>{_?.(e),!e.defaultPrevented&&(I(e),N(e))},[_,I,N]),ne=(0,J.useCallback)(e=>{b?.(e),!e.defaultPrevented&&(L(e),P(e))},[b,L,P]),re=(0,J.useCallback)(e=>{x?.(e),!e.defaultPrevented&&R(e)},[x,R]);return(0,X.jsx)(k,{value:c,children:(0,X.jsx)(ve,{ref:g,variant:d,paddingBlock:Lt[c],dividers:f,xstyle:p,className:m,style:h,children:(0,X.jsxs)(`div`,{ref:M,role:`toolbar`,"aria-label":o,"aria-orientation":u,onKeyDown:te,onFocus:ne,onBlur:re,...v(r(`toolbar`,{size:c}),n(T?Z.baseGrid:Z.baseFlex,u===`vertical`&&Z.vertical,It.base,Q.gap(j),O&&Q.tabIndicatorBottom(`calc(-1 * (${Rt[c]} + 1px))`))),...w,children:[T?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{...n(Z.startSlot,A.inset($[c]),Q.gap(j)),children:e}),(0,X.jsx)(`div`,{...n(Z.centerSlot,Q.gap(j)),children:t}),(0,X.jsx)(`div`,{...n(Z.endSlot,A.inset($[c]),Q.gap(j)),children:i})]}):(0,X.jsxs)(X.Fragment,{children:[E&&(0,X.jsx)(`div`,{...n(Z.startSlot,!D&&Z.startOnly,A.inset($[c]),Q.gap(j)),children:e}),D&&(0,X.jsx)(`div`,{...n(Z.endSlot,!E&&Z.endOnly,A.inset($[c]),Q.gap(j)),children:i})]}),F]})})})}zt.displayName=`Toolbar`;function Bt(e){return(0,X.jsx)(O,{children:(0,X.jsx)(Vt,{...e})})}function Vt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o,showComposer:s=!0,leading:c}){let u=D(),f=u(`@theorem.agent.handle`,{handle:e}),{blocks:p,callStarts:m}=mt(n,t),h=u(`@theorem.live.new_session`),g=Object.fromEntries(m.map(e=>[e,h])),_=s?(0,X.jsx)(ye,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o}):null;return(0,X.jsxs)(l,{height:`100%`,children:[c,(0,X.jsx)(d,{size:`fill`,children:p.length>0?(0,X.jsx)(ee,{label:u(`@theorem.panel.captions.name`),children:(0,X.jsx)(be,{blocks:p,dividers:g,handle:f,streaming:ht(t)})}):(0,X.jsx)(l,{height:`100%`,vAlign:`center`,padding:4,children:(0,X.jsx)(_e,{icon:(0,X.jsx)(b,{icon:Me,size:`lg`,color:`secondary`}),title:u(`@theorem.panel.captions.empty.title`),description:u(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),_]})}var Ht=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 z(`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 _(),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 z(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new z(`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,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`,...fe(t,e.profile.labels,H)}),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:H});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 Ut(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new Ht(e,t,r)}}var Wt=720,Gt=320;function Kt({theme:e,mode:t,labels:n,...r}){return(0,X.jsx)(g,{theme:e,mode:t,children:(0,X.jsx)(O,{labels:n,children:(0,X.jsx)(qt,{...r})})})}function qt({iface:e,connection:t,trace:n,slots:r,context:i,pageTools:a}){let s=D(),u=Pt(e,t,{slots:r,context:i,pageTools:a}),d=(0,J.useRef)(null),f=F(e,u.traces,n),p=C(d,!0),m={name:s(`@theorem.panel.captions.name`),show:s(`@theorem.panel.captions.show`),hide:s(`@theorem.panel.captions.hide`),resize:s(`@theorem.panel.captions.resize`)},h=(0,X.jsx)(S,{labels:m,icon:(0,X.jsx)(b,{icon:we}),panelId:p.id,open:p.open,onToggle:p.toggle});return u.callStarted?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(x,{children:f.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(c,{height:`fill`,end:(0,X.jsx)(w,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,X.jsx)(Qt,{model:u})}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(l,{height:`100%`,paddingInline:3,paddingBlockEnd:4,children:(0,X.jsx)(Yt,{model:u,captionsToggle:h})})})})})})}),(0,X.jsx)(rn,{prompt:u.gatePrompt,agent:s(`@theorem.agent.handle`,{handle:u.handle}),onResolve:u.resolveGateDecision})]}):(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(x,{children:f.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(Jt,{model:u})})})})}function Jt({model:e}){let t=D();return(0,X.jsx)(l,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,X.jsx)(R,{axis:`horizontal`,width:`100%`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:Te,gap:8,children:[(0,X.jsxs)(l,{gap:1,children:[(0,X.jsx)(T,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,X.jsxs)(u,{gap:2,wrap:`wrap`,children:[(0,X.jsx)(j,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:je}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,X.jsx)(j,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,X.jsx)(b,{icon:Pe}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Yt({model:e,captionsToggle:t}){let n=D(),r=Xt();return(0,X.jsx)(l,{ref:r,height:`100%`,hAlign:`center`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:Wt,height:`100%`,gap:3,children:[(0,X.jsxs)(l,{gap:.5,children:[(0,X.jsx)(T,{type:`label`,color:`secondary`,children:n(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{size:`sm`,color:`secondary`,children:E(n,e.liveState,e.activeTool)})]}),e.failure?(0,X.jsx)(L,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,X.jsx)(L,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,X.jsx)(d,{size:`fill`,children:(0,X.jsx)(l,{height:`100%`,vAlign:`end`,children:(0,X.jsx)(l,{width:`100%`,height:Gt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,X.jsx)(xe,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,X.jsx)(Zt,{model:e,captionsToggle:t})]})})}function Xt(){let e=(0,J.useRef)(null);return(0,J.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 Zt({model:e,captionsToggle:t}){let n=D(),r=!e.sessionActive,i=[];return e.voiceAvailable&&i.push((0,X.jsx)(W,{label:n(`@theorem.live.microphone`),tooltip:n(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:r,icon:(0,X.jsx)(b,{icon:f}),pressedIcon:(0,X.jsx)(b,{icon:ke}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&(i.push((0,X.jsx)(W,{label:n(`@theorem.live.camera`),tooltip:n(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:r,icon:(0,X.jsx)(b,{icon:Pe}),pressedIcon:(0,X.jsx)(b,{icon:Ne}),onPressedChange:()=>{e.handleToggleVideo()}},`video`)),e.isVideoOn&&i.push((0,X.jsx)(M,{label:n(`@theorem.live.flip_camera`),tooltip:n(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:r,icon:(0,X.jsx)(b,{icon:Oe}),onClick:()=>{e.handleFlipCamera()}},`flip`))),i.push((0,X.jsx)(J.Fragment,{children:t},`captions`),e.canRestart?(0,X.jsx)(M,{label:n(`@theorem.live.start_call`),tooltip:n(`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:je}),onClick:()=>{e.handleRestart()}},`call`):(0,X.jsx)(M,{label:n(`@theorem.live.end_call`),tooltip:n(`@theorem.live.end_call`),variant:`destructive`,isDisabled:r,icon:(0,X.jsx)(b,{icon:Ae}),onClick:e.handleEnd},`call`)),(0,X.jsx)(zt,{label:n(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,X.jsx)(u,{gap:2,vAlign:`center`,children:i})})}function Qt({model:e}){return(0,X.jsx)(Bt,{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,X.jsx)($t,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function $t({video:e,facingMode:t}){let n=D(),r=(0,J.useRef)(null);return(0,J.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,J.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,X.jsx)(ie,{ratio:4/3,fit:`cover`,children:(0,X.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var en=4,tn=432,nn={background:`transparent`,boxShadow:`none`};function rn({prompt:e,agent:t,onResolve:n}){return(0,X.jsx)(N,{isOpen:e!==null,purpose:`required`,width:tn,padding:en,style:nn,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,X.jsx)(oe,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,X.jsx)(ae,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function an({runtime:e,...t}){let{payload:n}=t;return(0,X.jsx)(sn,{...t,connect:()=>e?Ut(n,e):re(n)})}function on({endpoint:e,...t}){return(0,X.jsx)(sn,{...t,connect:()=>({createSocket:()=>new WebSocket(e.replace(/^http/,`ws`))})})}function sn({payload:e,note:t,connect:n,trace:r,slots:i,context:a}){let o=(0,J.useMemo)(()=>h(e),[e]),s=(0,J.useMemo)(()=>ne(e),[e]);return o.type===`live`?(0,X.jsx)(Kt,{labels:se,iface:o,connection:()=>(t(),n()),trace:r,slots:i,context:a,pageTools:s}):null}export{on as ProjectLive,an as StudioLive};
5
+ `):[])},[r,n])}var vt=.62,yt=400;function bt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function xt(e,t){let n=t?.facingMode??`user`;return bt(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 z(`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`,vt).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,yt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await bt(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 St(e){let t=(0,J.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,J.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,J.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=>it(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,J.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await xt(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,J.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,J.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,J.useCallback)(async()=>{t(),await n()},[n,t])}}function Ct(e){return new de(e.kind,e.error,e.message)}function Y(e){e.gateCallId===void 0&&e.clearActiveTool()}function wt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Y(t):e.phase===`error`?(t.reportFailure(Ct(e.failure)),Y(t)):t.setActiveTool(e.name)}function Tt(e,t){e.type===`done`?(t.clearInterim(),Y(t)):e.type===`tool`&&wt(e.tool,t)}function Et(e){let[t,n]=(0,J.useState)(`disconnected`),[r,i]=(0,J.useState)(null),a=(0,J.useRef)({input:0,output:0}),o=(0,J.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,J.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(!1),[f,m]=(0,J.useState)(null),[h,g]=(0,J.useState)($e),[_,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(``),[C,ee]=(0,J.useState)(!1),[w,T]=(0,J.useState)([]),[E,D]=(0,J.useState)(!1),[O,k]=(0,J.useState)(null),[A,j]=(0,J.useState)(`user`),M=(0,J.useRef)(null),N=(0,J.useRef)(h),P=(0,J.useRef)(c),F=(0,J.useRef)(w),I=(0,J.useRef)(t);return N.current=h,P.current=c,F.current=w,I.current=t,(0,J.useEffect)(()=>{C&&D(!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:m,captions:h,setCaptions:g,failure:_,reportFailure:(0,J.useCallback)(t=>{v(p(t,e))},[e]),clearFailure:(0,J.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,J.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,J.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:ee,sessionPermissions:w,setSessionPermissions:T,everConnected:E,videoPreview:O,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,J.useCallback)(()=>{g($e())},[]),stopVideo:(0,J.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),d(!1)},[])}}function Dt(e){let[t,n]=(0,J.useState)(null),r=(0,J.useRef)(t);r.current=t;let i=(0,J.useRef)(null),a=(0,J.useRef)(null),o=(0,J.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,J.useCallback)(t=>{e.setCaptions(e=>ct(e,t)),Tt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>gt(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:e.setActiveTool})},[e,o]),waitForGateDecision:(0,J.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,J.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,J.useCallback)(()=>{a.current?.(new z(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}async function Ot(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.sessionPermissions,s=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,c=await t({callId:i,operationId:a}),l=new Set;for(;c.status!==`settled`;){if(c.status===`dispatched`){if(l.has(c.grantId))return;l.add(c.grantId);let e=c.grantId,n=c.arguments,r=s?await Promise.resolve().then(()=>s(n,{callId:i,operationId:a})).catch(()=>void 0):void 0;c=await t({callId:i,operationId:a,grantId:e,...r?{output:r.output}:{unanswered:!0}});continue}let{gate:u}=c;if(u.kind===`page`){await t({callId:i,operationId:a,decision:`deny`});return}let d=await e.waitForGateDecision({callId:i,toolName:n,input:u.preparedArguments??r,gate:u});if(d===`withdrawn`)return;let f=te({toolName:n,gate:u,sessionPermissions:o,resolution:d});if(f.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}o=f.sessionPermissions,e.setSessionPermissions(f.sessionPermissions),c=await t({callId:i,decision:`approve`,operationId:a,...f.secret===void 0?{}:{secret:f.secret}})}}function kt(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 At(e,t,n,r){r.setCaptions(r=>it(r,e,t,n?.interim))}async function jt(e,t,n,r,i){r.setActiveTool(e),r.clearFailure();let a=i.current;if(!a)r.reportFailure(new z(`request`,`live tool call with no session client`));else try{await Ot({pageTools:r.pageTools,executeToolOnRelay:e=>a.executeToolOnRelay(e),name:e,toolArgs:t,callId:n.callId,operationId:n.operationId,sessionPermissions:r.sessionPermissionsRef.current,setSessionPermissions:e=>{r.sessionPermissionsRef.current=e,r.setSessionPermissions(e)},waitForGateDecision:r.waitForGateDecision})}catch(e){r.reportFailure(e)}finally{r.gatePromptRef.current||r.setActiveTool(null)}}function Mt(e){let t=(0,J.useRef)(null),n=(0,J.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,J.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Qe({...e,slots:r.slots,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{kt(e,n.current)},onTranscript:(e,t,r)=>{At(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):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)},onToolCall:(e,r,i)=>jt(e,r,i,n.current,t)});return t.current=i,i},[]),clearClient:(0,J.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Nt(e,t,n,r){let[i,a]=(0,J.useState)(!1),[o,s]=(0,J.useState)(!1),c=(0,J.useRef)(!1),l=(0,J.useCallback)(t=>{c.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,J.useEffect)(()=>{n&&c.current&&(c.current=!1,e.handleToggleVideo())},[e,n]);let u=(0,J.useCallback)(()=>{c.current=!1,e.teardownSession(),s(!0)},[e]),[d,f]=(0,J.useState)([]),p=(0,J.useCallback)(async()=>{let n=t.current.turns;f(e=>et(e,n)),s(!1),await e.handleRestart()},[e,t]),m=(0,J.useRef)(e.teardownSession);return m.current=e.teardownSession,(0,J.useEffect)(()=>()=>{m.current()},[]),{callStarted:i,ended:o,pastCalls:d,startCall:l,handleEnd:u,handleRestart:p}}function Pt(e,t,n={}){let r=Et(e.labels),i=Dt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,J.useRef)(t);a.current=t;let o=U(e.live.ingress,`audio`),s=U(e.live.ingress,`video`),c=U(e.live.ingress,`text`),l=(0,J.useMemo)(()=>Fe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,J.useMemo)(m,[]),{clientRef:d,ensureClient:f,clearClient:p}=Mt({slots:n.slots,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,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),h=St({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,ended:_,pastCalls:v,startCall:y,handleEnd:b,handleRestart:x}=Nt(h,r.captionsRef,r.sessionActive,s),S=JSON.stringify(n.context);(0,J.useEffect)(()=>{d.current?.setContext(S===void 0?void 0:JSON.parse(S))},[d,S]);let C=JSON.stringify(n.slots);return(0,J.useEffect)(()=>{d.current?.setSlots(C===void 0?void 0:JSON.parse(C))},[d,C]),_t(e.tools.page,n.pageTools),{handle:e.identity.handle,traces:u,callStarted:g,pastCalls:v,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||_||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:b,startCall:y,handleRestart:x,handleSendText:h.handleSendText,handleToggleMic:h.handleToggleMic,handleFlipCamera:h.handleFlipCamera,handleToggleVideo:h.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var X=t(),Ft={0:`--spacing-0`,.5:`--spacing-0-5`,1:`--spacing-1`,1.5:`--spacing-1-5`,2:`--spacing-2`,3:`--spacing-3`,4:`--spacing-4`,5:`--spacing-5`,6:`--spacing-6`,8:`--spacing-8`,10:`--spacing-10`},Z={baseFlex:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x1qughib`,$$css:!0},baseGrid:{k1xSpc:`xrvj5dj`,kumcoG:`x134kloy`,kGNEyG:`x6s0dn4`,$$css:!0},vertical:{kXwgrk:`xdt5ytf`,kGNEyG:`x1qjc9v5`,$$css:!0},startSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,$$css:!0},centerSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,k7Eaqz:`xeuugli`,$$css:!0},endSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x13a6bvl`,$$css:!0},startOnly:{kUk6DE:`x845mor`,$$css:!0},endOnly:{keTefX:`xvc5jky`,$$css:!0}},It={base:{kAzted:`x1gdqauq`,$$css:!0}},Q={gap:e=>[{kOIVth:e==null?e:`x1pidvrl`,$$css:!0},{"--x-gap":(e=>typeof e==`number`?e+`px`:e??void 0)(e)}],tabIndicatorBottom:e=>[{"--_tab-indicator-bottom":e==null?e:`xbrl7fg`,$$css:!0},{"--x---_tab-indicator-bottom":e??void 0}]},Lt={sm:2,md:2,lg:2},Rt={sm:a[`--spacing-2`],md:a[`--spacing-2`],lg:a[`--spacing-2`]},$={sm:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,md:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,lg:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`};function zt({startContent:e,centerContent:t,endContent:i,label:o,size:c=`md`,gap:l=1,orientation:u=`horizontal`,variant:d=`transparent`,dividers:f,xstyle:p,className:m,style:h,ref:g,onKeyDown:_,onFocus:b,onBlur:x,role:S,"aria-label":C,"aria-orientation":ee,...w}){let T=t!=null,E=e!=null,D=i!=null,O=f?.includes(`bottom`)??!1,j=a[Ft[l]],{listRef:M,handleKeyDown:N,handleFocus:P}=y({itemSelector:`button, input, [tabindex]`,boundarySelector:`[role="toolbar"], [popover]`,orientation:u,hasRovingTabIndex:!0,hasCaretGuard:!0}),{hintElement:F,onKeyDown:I,onFocus:L,onBlur:R}=s({orientation:u}),te=(0,J.useCallback)(e=>{_?.(e),!e.defaultPrevented&&(I(e),N(e))},[_,I,N]),ne=(0,J.useCallback)(e=>{b?.(e),!e.defaultPrevented&&(L(e),P(e))},[b,L,P]),re=(0,J.useCallback)(e=>{x?.(e),!e.defaultPrevented&&R(e)},[x,R]);return(0,X.jsx)(k,{value:c,children:(0,X.jsx)(ye,{ref:g,variant:d,paddingBlock:Lt[c],dividers:f,xstyle:p,className:m,style:h,children:(0,X.jsxs)(`div`,{ref:M,role:`toolbar`,"aria-label":o,"aria-orientation":u,onKeyDown:te,onFocus:ne,onBlur:re,...v(r(`toolbar`,{size:c}),n(T?Z.baseGrid:Z.baseFlex,u===`vertical`&&Z.vertical,It.base,Q.gap(j),O&&Q.tabIndicatorBottom(`calc(-1 * (${Rt[c]} + 1px))`))),...w,children:[T?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{...n(Z.startSlot,A.inset($[c]),Q.gap(j)),children:e}),(0,X.jsx)(`div`,{...n(Z.centerSlot,Q.gap(j)),children:t}),(0,X.jsx)(`div`,{...n(Z.endSlot,A.inset($[c]),Q.gap(j)),children:i})]}):(0,X.jsxs)(X.Fragment,{children:[E&&(0,X.jsx)(`div`,{...n(Z.startSlot,!D&&Z.startOnly,A.inset($[c]),Q.gap(j)),children:e}),D&&(0,X.jsx)(`div`,{...n(Z.endSlot,!E&&Z.endOnly,A.inset($[c]),Q.gap(j)),children:i})]}),F]})})})}zt.displayName=`Toolbar`;function Bt(e){return(0,X.jsx)(O,{children:(0,X.jsx)(Vt,{...e})})}function Vt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o,showComposer:s=!0,leading:c}){let u=D(),f=u(`@theorem.agent.handle`,{handle:e}),{blocks:p,callStarts:m}=mt(n,t),h=u(`@theorem.live.new_session`),g=Object.fromEntries(m.map(e=>[e,h])),_=s?(0,X.jsx)(De,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o}):null;return(0,X.jsxs)(l,{height:`100%`,children:[c,(0,X.jsx)(d,{size:`fill`,children:p.length>0?(0,X.jsx)(ee,{label:u(`@theorem.panel.captions.name`),children:(0,X.jsx)(xe,{blocks:p,dividers:g,handle:f,streaming:ht(t)})}):(0,X.jsx)(l,{height:`100%`,vAlign:`center`,padding:4,children:(0,X.jsx)(_e,{icon:(0,X.jsx)(b,{icon:Me,size:`lg`,color:`secondary`}),title:u(`@theorem.panel.captions.empty.title`),description:u(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),_]})}var Ht=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 z(`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 _(),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 z(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new z(`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,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`,...fe(t,e.profile.labels,H)}),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:H});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 Ut(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new Ht(e,t,r)}}var Wt=720,Gt=320;function Kt({theme:e,mode:t,labels:n,...r}){return(0,X.jsx)(g,{theme:e,mode:t,children:(0,X.jsx)(O,{labels:n,children:(0,X.jsx)(qt,{...r})})})}function qt({iface:e,connection:t,trace:n,slots:r,context:i,pageTools:a}){let s=D(),u=Pt(e,t,{slots:r,context:i,pageTools:a}),d=(0,J.useRef)(null),f=F(e,u.traces,n),p=C(d,!0),m={name:s(`@theorem.panel.captions.name`),show:s(`@theorem.panel.captions.show`),hide:s(`@theorem.panel.captions.hide`),resize:s(`@theorem.panel.captions.resize`)},h=(0,X.jsx)(S,{labels:m,icon:(0,X.jsx)(b,{icon:be}),panelId:p.id,open:p.open,onToggle:p.toggle});return u.callStarted?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(x,{children:f.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(c,{height:`fill`,end:(0,X.jsx)(w,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,X.jsx)(Qt,{model:u})}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(l,{height:`100%`,paddingInline:3,paddingBlockEnd:4,children:(0,X.jsx)(Yt,{model:u,captionsToggle:h})})})})})})}),(0,X.jsx)(rn,{prompt:u.gatePrompt,agent:s(`@theorem.agent.handle`,{handle:u.handle}),onResolve:u.resolveGateDecision})]}):(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(x,{children:f.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(Jt,{model:u})})})})}function Jt({model:e}){let t=D();return(0,X.jsx)(l,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,X.jsx)(R,{axis:`horizontal`,width:`100%`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:we,gap:8,children:[(0,X.jsxs)(l,{gap:1,children:[(0,X.jsx)(T,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,X.jsxs)(u,{gap:2,wrap:`wrap`,children:[(0,X.jsx)(j,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:je}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,X.jsx)(j,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,X.jsx)(b,{icon:Pe}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Yt({model:e,captionsToggle:t}){let n=D(),r=Xt();return(0,X.jsx)(l,{ref:r,height:`100%`,hAlign:`center`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:Wt,height:`100%`,gap:3,children:[(0,X.jsxs)(l,{gap:.5,children:[(0,X.jsx)(T,{type:`label`,color:`secondary`,children:n(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{size:`sm`,color:`secondary`,children:E(n,e.liveState,e.activeTool)})]}),e.failure?(0,X.jsx)(L,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,X.jsx)(L,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,X.jsx)(d,{size:`fill`,children:(0,X.jsx)(l,{height:`100%`,vAlign:`end`,children:(0,X.jsx)(l,{width:`100%`,height:Gt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,X.jsx)(Te,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,X.jsx)(Zt,{model:e,captionsToggle:t})]})})}function Xt(){let e=(0,J.useRef)(null);return(0,J.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 Zt({model:e,captionsToggle:t}){let n=D(),r=!e.sessionActive,i=[];return e.voiceAvailable&&i.push((0,X.jsx)(W,{label:n(`@theorem.live.microphone`),tooltip:n(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:r,icon:(0,X.jsx)(b,{icon:f}),pressedIcon:(0,X.jsx)(b,{icon:ke}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&(i.push((0,X.jsx)(W,{label:n(`@theorem.live.camera`),tooltip:n(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:r,icon:(0,X.jsx)(b,{icon:Pe}),pressedIcon:(0,X.jsx)(b,{icon:Ne}),onPressedChange:()=>{e.handleToggleVideo()}},`video`)),e.isVideoOn&&i.push((0,X.jsx)(M,{label:n(`@theorem.live.flip_camera`),tooltip:n(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:r,icon:(0,X.jsx)(b,{icon:Oe}),onClick:()=>{e.handleFlipCamera()}},`flip`))),i.push((0,X.jsx)(J.Fragment,{children:t},`captions`),e.canRestart?(0,X.jsx)(M,{label:n(`@theorem.live.start_call`),tooltip:n(`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:je}),onClick:()=>{e.handleRestart()}},`call`):(0,X.jsx)(M,{label:n(`@theorem.live.end_call`),tooltip:n(`@theorem.live.end_call`),variant:`destructive`,isDisabled:r,icon:(0,X.jsx)(b,{icon:Ae}),onClick:e.handleEnd},`call`)),(0,X.jsx)(zt,{label:n(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,X.jsx)(u,{gap:2,vAlign:`center`,children:i})})}function Qt({model:e}){return(0,X.jsx)(Bt,{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,X.jsx)($t,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function $t({video:e,facingMode:t}){let n=D(),r=(0,J.useRef)(null);return(0,J.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,J.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,X.jsx)(ie,{ratio:4/3,fit:`cover`,children:(0,X.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var en=4,tn=432,nn={background:`transparent`,boxShadow:`none`};function rn({prompt:e,agent:t,onResolve:n}){return(0,X.jsx)(N,{isOpen:e!==null,purpose:`required`,width:tn,padding:en,style:nn,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,X.jsx)(oe,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,X.jsx)(ae,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function an({runtime:e,...t}){let{payload:n}=t;return(0,X.jsx)(sn,{...t,connect:()=>e?Ut(n,e):re(n)})}function on({endpoint:e,...t}){return(0,X.jsx)(sn,{...t,connect:()=>({createSocket:()=>new WebSocket(e.replace(/^http/,`ws`))})})}function sn({payload:e,note:t,connect:n,trace:r,slots:i,context:a}){let o=(0,J.useMemo)(()=>h(e),[e]),s=(0,J.useMemo)(()=>ne(e),[e]);return o.type===`live`?(0,X.jsx)(Kt,{labels:se,iface:o,connection:()=>(t(),n()),trace:r,slots:i,context:a,pageTools:s}):null}export{on as ProjectLive,an as StudioLive};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{p as r}from"./fieldParts-B7DYLgh4.js";import{t as i}from"./Icon-BqkS-pIq.js";import{t as a}from"./Text-BOqCfzZC.js";import{n as o,t as s}from"./IconButton-DVUFx-8p.js";import{t as c}from"./createReactComponent-CZwsv6DD.js";import{n as l,t as u}from"./ScrollableArea-BHfY7sWH.js";import{n as d,t as f}from"./Center-nHS1JSux.js";import{t as p}from"./IconEye-BB5aY-wQ.js";import{t as m}from"./IconSearch-BTx66a40.js";import{r as h,s as g,t as _}from"./tree-DfG6CXsC.js";import{F as v,i as y}from"./workspace-CzTPlUdi.js";import{a as b,n as x,r as S}from"./studio-session-yEqFQo5o.js";import{t as C}from"./EmptyState-C_uF9Wyj.js";import{$ as w,Et as T,F as E,J as D,Lt as O,Q as k,Rt as A,Tt as j,X as M,Z as N,et as P,n as F,nt as I,u as L}from"./index-3PUx0L6S.js";var R=c(`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`}]]),z=c(`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`}]]),B=c(`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`}]]),V=c(`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 H(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 U(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId||`New model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function W(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,y(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,g(e.key)])),a=v(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:y(e.key),kind:`agent`,label:n||`New agent`,note:o?`${s} · ${o}`:s,opens:y(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:U(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=y(e,t);return s.has(n)?n:y(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=h(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:y(t.key,_(i.key))});let s=y(t.key,_(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId||`New 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!==y(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=g(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||`New 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?[g(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):y(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 b=H([...d.values()],n,m),x=new Map(b.map((e,t)=>[e.id,t])),S=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[S({label:`Providers`,nodes:H([...l.values()],n,x)}),S({label:`Shared settings`,nodes:H(p,n,m)},{label:`Models`,nodes:b}),S({label:`Profiles`,nodes:o}),S({label:`Tools`,nodes:H(f,n,m)})].filter(e=>e.length>0),links:n}}function G(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 K(e){let t=G(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 ee(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 te(e,t){let n=typeof t==`string`?[t]:t,r=K(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}var ne={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 re(e,t){let n=G(e),r=new Map;for(let{link:i,from:a,to:o}of K(e)){if(a!==t&&o!==t)continue;let e=ne[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 ie(e){return e.kind===`tool`||e.kind===`shared`?2:1}var ae=24,q=8,J=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return K(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function se(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||ie(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(oe(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:S,headings:C,boxes:w,ports:E}=x,{right:D,bottom:O}=x,{spans:k,rails:A}=_(E),M=a/2,N=Math.max(o/2,u),P=[],F=new Map,I=Math.max(a,...y.map(e=>e*J)),L=K(e).flatMap(({link:e,from:t,to:n})=>{let i=E.get(e.from),o=E.get(e.to);if(!i||!o)return[];let s=w.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)+M&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+M;return D=Math.max(D,l),[{link:e,from:t,to:n,d:j({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=k.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?j(p,m):T(p,m,b,q),S=(e,t)=>t>e.y-N&&t<e.y+e.height+N,C=Math.abs(m.x-p.x)<I+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/ae)).some(t=>t.x>e.x&&t.x<e.x+e.width&&S(e,t.y)));if(C.length===0)return[{link:e,from:t,to:n,d:x.d}];let[L,R]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],z=e=>{let t=[...C];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-N:Math.max(...t.map(e=>e.y+e.height))+N,r=[...s,...P].filter(e=>!t.includes(e)&&e.x<R&&e.x+e.width>L&&S(e,n));if(r.length===0)return n;t.push(...r)}},B=e=>Math.abs(i.y-e)+Math.abs(o.y-e),V=`${f}:${y}`,H=F.get(V)??(()=>{let[e,t]=[z(-1),z(1)],n=e>=0&&B(e)<=B(t)?e:t;return P.push({id:``,x:L,y:n-q+N,width:R-L,height:2*(q-N)}),F.set(V,n),n})();O=Math.max(O,H);let U=d?p.x+l*J:b,W=d?b:m.x-l*J,G={x:(U+W)/2,y:H};return[{link:e,from:t,to:n,d:T(p,G,U,q).d+T(G,m,W,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,D)+l,height:Math.max(O,l)+l,nodes:S,headings:C,lines:L}}var Y=e(n(),1),ce={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${x}.map`:`${x}.map.project:${e}`;function le(e){if(!S(e))return{};let t={};for(let[n,r]of Object.entries(e))S(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function ue(e){try{let t=JSON.parse(b()?.getItem(X(e))??`null`);return S(t)?{tokens:le(t.tokens),detail:le(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:ce}catch{return ce}}function de(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t,o=Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0;try{o?b()?.removeItem(X(e)):b()?.setItem(X(e),JSON.stringify(t))}catch{}}function fe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function pe(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var me=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function he(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=me(e.left,a.scrollWidth-a.clientWidth),r=me(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var ge=e=>e.button===0&&e.pointerType!==`touch`;function _e(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ve(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!ge(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),_e(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=t(),ye={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},be={...ye,node:{width:240,height:84}},xe=28;function Se(e){return e.length>xe?`${e.slice(0,27)}…`:e}function Ce({kind:e,type:t,note:n}){return(e===`agent`?w(t):void 0)||(e===`tool`?P(t??``):e===`model`?L(n)??F.modelBinding:e===`provider`?A:e===`shared`&&t&&Object.hasOwn(F,t)?F[t]:e===`agent`?k.text:O)}function we(e){return Object.hasOwn(F,e)?F[e]:O}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Te=4,Ee=24,De={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function Oe(e){let t=D()?.name,[n,r]=(0,Y.useState)(()=>ue(t)),i=e=>{r(e),de(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:te(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function ke(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!ge(o))return;let c;_e(o,(e,r)=>{!c&&Math.hypot(e,r)<Te||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?De[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Ee,0),c=Math.max(o.y+a.y*Ee,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function Ae(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{let n=new Set,r=new Set;if(t===void 0)return[n,r];n.add(t);for(let{link:i,from:a,to:o}of e.lines)if([i.from,i.to,a,o].includes(t)){r.add(i);for(let e of[i.from,i.to,a,o])n.add(e)}return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function je(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return he(n,e=>{let{left:t,top:r}=pe(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Me(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:s,tidy:c}=n,l=[];e&&e.id!==r&&l.push({label:`Show only its family`,icon:B,onClick:()=>{o(e.id)}});let u=e?.opens;u!==void 0&&l.push({label:`Open`,icon:d,onClick:()=>{t(u)}}),e&&l.push({type:`divider`});let f={label:`Show everything`,icon:p,onClick:()=>{o(void 0)}};return[...l,...r===void 0?[]:[f],{label:i?`Collapse`:`Expand`,icon:i?z:R,onClick:s},{label:`Tidy`,icon:V,isDisabled:!a,onClick:c}]}function Ne({actions:e,query:t,onQuery:n,onClose:a}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:h,tidy:g}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(l,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:m,hasClear:!0,value:t,onChange:n}),c!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(i,{icon:p,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(i,{icon:V,size:`sm`}),onClick:g}),(0,Z.jsx)(s,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(i,{icon:u?z:R,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:h}),(0,Z.jsx)(s,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(i,{icon:r,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Pe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(M,{id:t.id,label:Se(t.long??t.label),icon:Ce(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>xe?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:r,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)(i,{icon:Ce(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:ie(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":r||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)(i,{icon:we(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Ie({workspace:e,shared:t,selected:n,onOpen:r,onClose:o}){let{expanded:s,family:c,map:l,moved:d,put:p,showFamily:h,expand:g}=Oe((0,Y.useMemo)(()=>W(e,t),[e,t])),[_,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>ee(l,_),[l,_]),b=(0,Y.useMemo)(()=>_.trim()===``?l:te(l,y),[l,_,y]),x=_.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),w=s?be:ye,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),D=N(S,T),O=(0,Y.useMemo)(()=>se(b,w,{moved:d,widths:D,detail:s}),[b,w,s,d,D]),k=b.columns.flat().flatMap(e=>e.nodes),A=k.find(e=>Q(e,n))?.id;je(S,c,{place:A===void 0?void 0:O.nodes[A],sizes:w});let{dragging:j,draggable:M}=ke(O,d,p),{panning:P,pan:F}=ve(`[data-map-node]`),{lit:I,on:L,onLines:R,lights:z}=Ae(O),B={family:c,expanded:s,isMoved:k.some(e=>Object.hasOwn(d,e.id)),showFamily:h,expand:g,tidy:()=>{p({},!0)}},[V,H]=(0,Y.useState)(),U=Me(k.find(e=>e.id===V),r,B),G=s?Fe:Pe,K=k.find(e=>Q(e,n))?.id,ne=e=>R.has(e.link)?2:+(e.from===K||e.to===K),ie=[...O.lines].sort((e,t)=>ne(e)-ne(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&c!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),h(void 0)))},children:[(0,Z.jsx)(u,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(E,{items:U,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":I===void 0||j!==void 0?void 0:``,"data-panning":P?``:void 0,onPointerDown:F,onContextMenuCapture:e=>{H(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(O.width)}px`,"--map-height":`${String(O.height)}px`,"--map-slot":`${String(w.node.width)}px`,"--map-line":`${String(w.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:O.width,height:O.height,"aria-hidden":`true`,children:ie.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":R.has(e)?``:void 0,"data-open":t===K||n===K?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),O.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)),k.map(e=>{let t=O.nodes[e.id];return t&&(0,Z.jsx)(G,{node:e,place:t,joins:re(b,e.id),selected:n,on:L,isFound:y.includes(e.id),isDragging:j===e.id,onOpen:r,lights:z,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(f,{className:`studio-map-nothing`,children:(0,Z.jsx)(C,{headingLevel:2,icon:(0,Z.jsx)(i,{icon:m,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Ne,{actions:B,query:_,onQuery:v,onClose:o})]})}export{Ie as StudioMap};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{n as r,t as i}from"./SegmentedControlItem-BBGRPrxp.js";import{t as a}from"./VStack-CkVMcNiK.js";import{n as o,t as s}from"./StackItem-CQviqAfM.js";import{C as c,S as l,a as u,g as d,h as f,o as p,s as m}from"./browser-transport-BgmUaqDP.js";import{p as h}from"./fieldParts-B7DYLgh4.js";import{t as g}from"./Icon-BqkS-pIq.js";import{t as _}from"./Text-BOqCfzZC.js";import{n as v,t as y}from"./labels-provider-Bt3Q2GjB.js";import{n as b,t as x}from"./IconButton-DVUFx-8p.js";import{a as S,t as C}from"./Banner-DjmNbolt.js";import{g as ee,t as w}from"./studio-labels-CGR8sQpd.js";import{c as T}from"./host-patterns-F-KZIzkF.js";import{T as E}from"./shaped-data-C4yaGRz9.js";import{n as D}from"./trace-record-jV4PFwk_.js";import{n as O}from"./trace-schema-9CdEyG6Q.js";import{_ as te}from"./turn-client-CZG4gVtX.js";import{a as ne,i as re,o as ie,t as ae}from"./ConsoleFrame-DA11Fku_.js";import{S as oe,a as k,b as se,h as ce,y as le}from"./index-Dblg49i6.js";var A=e=>typeof e==`object`&&!!e&&!Array.isArray(e),j=(e,t)=>e.attributes[t],M=(e,t)=>{let n=j(e,t);return typeof n==`string`?n:void 0};function N(e,t,n){let r=j(t,n);return r===void 0?void 0:D(e,r)}function P(e,t,n){let r=N(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function F(e,t,n){let r=N(e,t,n);return Array.isArray(r)?r.filter(A):[]}var I=e=>Array.isArray(e.parts)?e.parts.filter(A):[],L=e=>BigInt(String(e.startTimeUnixNano)),R=(e,t)=>{let n=L(e)-L(t);return n===0n?0:n<0n?-1:1};function z(e){let t=e.endTimeUnixNano;if(!t)return;let n=L(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=z(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 B(e){let t=e.arguments;if(A(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return A(e)?e:{}}catch{return{}}}function V(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=I(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=V(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:B(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=M(n,`gen_ai.agent.name`);if(M(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var H=e=>M(e,`gen_ai.operation.name`);function he(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>H(e)===`chat`).toSorted(R).map(n=>{let r=pe(F(e,n,`gen_ai.output.messages`)),i=M(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=>H(e)===`execute_tool`).toSorted(R).map(t=>({name:M(t,`gen_ai.tool.name`)??``,result:P(e,t,`gen_ai.tool.call.result`),failed:M(t,`theorem.tool.outcome`)===`error`}))}function U(e,t){let n=F(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?I(n):[];return{text:r.flatMap(e=>e.type===`text`&&typeof e.content==`string`?[e.content]:[]).join(`
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{n as r,t as i}from"./SegmentedControlItem-BBGRPrxp.js";import{t as a}from"./VStack-CkVMcNiK.js";import{n as o,t as s}from"./StackItem-CQviqAfM.js";import{C as c,S as l,a as u,g as d,h as f,o as p,s as m}from"./browser-transport-LV_FgVKG.js";import{p as h}from"./fieldParts-B7DYLgh4.js";import{t as g}from"./Icon-BqkS-pIq.js";import{t as _}from"./Text-BOqCfzZC.js";import{n as v,t as y}from"./labels-provider-Bt3Q2GjB.js";import{n as b,t as x}from"./IconButton-DVUFx-8p.js";import{a as S,t as C}from"./Banner-DNuB7lhC.js";import{g as ee,t as w}from"./studio-labels-7sgmTzU-.js";import{c as T}from"./host-patterns-F-KZIzkF.js";import{T as E}from"./shaped-data-C4yaGRz9.js";import{n as D}from"./trace-record-jV4PFwk_.js";import{n as O}from"./trace-schema-9CdEyG6Q.js";import{_ as te}from"./turn-client-CZG4gVtX.js";import{a as ne,i as re,o as ie,t as ae}from"./ConsoleFrame-DRsXYFYa.js";import{S as oe,a as k,b as se,h as ce,y as le}from"./index-3PUx0L6S.js";var A=e=>typeof e==`object`&&!!e&&!Array.isArray(e),j=(e,t)=>e.attributes[t],M=(e,t)=>{let n=j(e,t);return typeof n==`string`?n:void 0};function N(e,t,n){let r=j(t,n);return r===void 0?void 0:D(e,r)}function P(e,t,n){let r=N(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function F(e,t,n){let r=N(e,t,n);return Array.isArray(r)?r.filter(A):[]}var I=e=>Array.isArray(e.parts)?e.parts.filter(A):[],L=e=>BigInt(String(e.startTimeUnixNano)),R=(e,t)=>{let n=L(e)-L(t);return n===0n?0:n<0n?-1:1};function z(e){let t=e.endTimeUnixNano;if(!t)return;let n=L(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=z(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 B(e){let t=e.arguments;if(A(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return A(e)?e:{}}catch{return{}}}function V(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=I(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=V(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:B(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=M(n,`gen_ai.agent.name`);if(M(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var H=e=>M(e,`gen_ai.operation.name`);function he(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>H(e)===`chat`).toSorted(R).map(n=>{let r=pe(F(e,n,`gen_ai.output.messages`)),i=M(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=>H(e)===`execute_tool`).toSorted(R).map(t=>({name:M(t,`gen_ai.tool.name`)??``,result:P(e,t,`gen_ai.tool.call.result`),failed:M(t,`theorem.tool.outcome`)===`error`}))}function U(e,t){let n=F(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?I(n):[];return{text:r.flatMap(e=>e.type===`text`&&typeof e.content==`string`?[e.content]:[]).join(`
2
2
  `),attachments:r.filter(e=>e.type===`blob`||e.type===`uri`).length}}function _e(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=D(e,i);if(!Array.isArray(a))continue;let o=[];for(let e of a)A(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=M(t,`gen_ai.tool.call.id`);n.push({type:`citation`,sources:o,...e?{callId:e}:{}})}}return n}function ve(e,t){let n=e.spans.filter(e=>H(e)===`execute_tool`).toSorted(R),r=new Set,i=(e,t)=>{let i=n.find(t=>M(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&M(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of F(e,t,`gen_ai.output.messages`))for(let t of I(n)){let n=V(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(...ye(e,t.name,n,B(t),i))}}let o=P(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=M(t,`theorem.stop.kind`)??`completed`;return a.push({type:`done`,stop:{kind:s}}),a}function ye(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=z(a),c=s?.startedAt??Number(L(a)/1000000n),l=s?.endedAt??c,u=P(e,a,`gen_ai.tool.call.result`),d=M(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:M(a,`theorem.tool.failure.code`)??`failed`,kind:`internal`,message:u},readBack:u}:{phase:`complete`,output:W(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}},..._e(e,a)]}function W(e){try{return JSON.parse(e)}catch{return e}}function be(e){let t=``,n,r=[];return e.forEach((e,i)=>{let a=E(e);if(!a||H(a)!==`invoke_agent`)return;let o=M(a,`gen_ai.agent.name`)??``;t||=o;let s=he(e),c=ge(e),l=r.at(-1);if(o!==t&&l){l.calls.push(...s),l.results.push(...c);return}n??=Number(L(a)/1000000n);let u=U(e,a);r.push({...u,calls:s,results:c,blocks:de(te({text:u.text},ve(e,a),{idPrefix:`recorded-${String(i)}`}),a)})}),{agent:t,turns:r,...n===void 0?{}:{recordedAt:n}}}function xe(e){if(e.failed)throw Error(e.result);let t=W(e.result);return A(t)?t:{result:t}}var Se=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 Ce(e,t,n){if(!e)return`The profile asked the model a ${Se(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 we(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=Ce(o[c],o.length,a);if(l)throw n({turn:r,call:c+1,reason:l}),new T(`request`,`Replay stopped: ${l}`);yield*o[c]?.events??[]}}),c=e=>()=>{let t=o(r).get(e)?.shift();if(!t)throw Error(`The recording has no further result for ${e}.`);return xe(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 G(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}:{}}})}function Te(e){return{...e,customTools:G(e.customTools),...e.dependencies?{dependencies:e.dependencies.map(e=>({...e,customTools:G(e.customTools)}))}:{}}}function K(e){return e.turns.flatMap(e=>e.blocks)}function Ee(e){let t=Array.isArray(e)?e:[e];return t.map((e,n)=>{let r=O.safeParse(e);if(r.success)return r.data;let i=t.length>1?` (record ${String(n+1)})`:``;throw new T(`request`,`This file is not a Theorem trace${i}.`)})}function De(e){let t;try{t=JSON.parse(e)}catch{throw new T(`request`,`This file is not JSON.`)}return Ee(t)}var q=e(n(),1),J=t();function Oe(e,t,n){return t?p(e,t,{conversationKey:k(),blocks:n}):f(e,n)}var Y=e=>`turn ${String(e+1)}`;function X({iface:e,feed:t,trace:n,card:r,conversation:i}){let a=S(e,t,n);return(0,J.jsxs)(ae,{inspector:a,maxWidth:`960px`,requestLabel:`Trace`,children:[r,i]})}function Z({iface:e,blocks:t,banner:n,chat:r}){let i=v();return(0,J.jsxs)(ne,{label:`Conversation`,children:[n,(0,J.jsx)(oe,{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 ke({onImport:e}){let[t,n]=(0,q.useState)(),[r,i]=(0,q.useState)(!1);return(0,J.jsxs)(a,{gap:2,children:[(0,J.jsx)(se,{label:`Trace file`,isLabelHidden:!0,mode:`dropzone`,accept:`application/json,.json`,isLoading:r,placeholder:`Drop a trace (.json) or choose a file`,value:null,changeAction:async t=>{let r=Array.isArray(t)?t[0]:t;if(r){i(!0);try{e({name:r.name,records:De(await r.text())}),n(void 0)}catch(e){n(e instanceof Error?e.message:String(e))}finally{i(!1)}}},onChange:()=>void 0}),t?(0,J.jsx)(C,{status:`error`,title:t}):null]})}var Ae=e=>e.recordedAt===void 0?void 0:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(e.recordedAt);function je({shown:e,onShown:t}){return(0,J.jsxs)(r,{label:`Show`,size:`sm`,value:e,onChange:e=>{t(e===`replayed`?`replayed`:`recorded`)},children:[(0,J.jsx)(i,{value:`recorded`,label:`Recorded`}),(0,J.jsx)(i,{value:`replayed`,label:`Replayed`})]})}function Me({controls:e}){let{script:t,payload:n}=e,r=t.turns.length,i=[t.agent||`No agent`,`${String(r)} ${r===1?`turn`:`turns`}`,Ae(t)];return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(o,{gap:2,vAlign:`center`,children:[(0,J.jsx)(s,{size:`fill`,children:(0,J.jsxs)(a,{gap:0,children:[(0,J.jsx)(_,{type:`label`,maxLines:1,children:e.opened.name}),(0,J.jsx)(_,{type:`supporting`,color:`secondary`,maxLines:1,children:i.filter(Boolean).join(` · `)})]})}),(0,J.jsx)(x,{label:`Clear trace`,variant:`ghost`,size:`sm`,icon:(0,J.jsx)(g,{icon:h,size:`sm`}),isDisabled:e.isRunning,onClick:e.onClear})]}),t.agent&&t.agent!==n.profile.id?(0,J.jsx)(C,{status:`info`,title:`Recorded with ${t.agent}; a replay runs through ${n.profile.id}.`}):null,r===0?(0,J.jsx)(C,{status:`info`,title:`This trace holds no conversation to replay.`}):null,(0,J.jsx)(le,{label:`Live tools`,description:`Run the profile's tools instead of answering them from the recording.`,value:e.liveTools,onChange:e.onLiveTools})]})}var Q=()=>void 0;function $({onImport:e,controls:t}){let n=t?.onReplay??Q;return(0,J.jsxs)(re,{title:`Trace`,onRun:n,actions:t?.shown?(0,J.jsx)(je,{shown:t.shown,onShown:t.onShown}):null,children:[(0,J.jsx)(ke,{onImport:e}),t?(0,J.jsx)(Me,{controls:t}):null,(0,J.jsx)(ie,{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??Q})]})}function Ne({status:e,turns:t,onContinue:n,onLive:r}){let[i,o]=(0,q.useState)(!1),[s,c]=(0,q.useState)(),l=e=>(0,J.jsx)(b,{label:`Continue live`,variant:`secondary`,size:`sm`,isLoading:i,onClick:async()=>{o(!0),c(void 0);try{await r(e)}catch(e){c(e instanceof Error?e.message:String(e)),o(!1)}}}),u=(()=>{switch(e.kind){case`running`:return(0,J.jsx)(C,{status:`info`,title:`Replaying ${Y(e.turn)} of ${String(t)}`});case`waiting`:return(0,J.jsx)(C,{status:`info`,title:`${Y(e.turn-1)} waits on you`,description:`Answer it in the conversation, then continue the replay.`,endContent:(0,J.jsx)(b,{label:`Continue replay`,variant:`secondary`,size:`sm`,onClick:()=>{n(e.turn)}})});case`missing`:return(0,J.jsx)(C,{status:`warning`,title:`Replay stopped before ${Y(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{turn:t,call:n,reason:r}=e.divergence;return(0,J.jsx)(C,{status:`warning`,title:`Replay stopped at ${Y(t)}, model call ${String(n)}`,description:r,endContent:l(t)})}case`failed`:return(0,J.jsx)(C,{status:`error`,title:`Replay stopped at ${Y(e.turn)}`,description:e.message,endContent:l(e.turn)});case`done`:return(0,J.jsx)(C,{status:`success`,title:`Replayed ${String(t)} ${t===1?`turn`:`turns`}`,description:`Every model call this profile made was one the recording answered.`})}})();return(0,J.jsxs)(a,{gap:1,children:[u,s?(0,J.jsx)(C,{status:`error`,title:s}):null]})}function Pe({payload:e,iface:t,trace:n,card:r,opened:i,script:a,shown:o,liveTools:s,runtime:d,onLive:f}){let p=(0,q.useRef)(void 0),[m,h]=(0,q.useState)({kind:`running`,turn:0}),[g]=(0,q.useState)(l),_=(0,q.useMemo)(()=>c(i.records),[i.records]),v=(0,q.useMemo)(()=>we(a,e.profile.id,e=>{p.current??=e}),[a,e.profile.id]),y=(0,q.useMemo)(()=>u(s?e:Te(e),{mode:`byok`,provider:v.provider,...s?{}:{toolHandlers:v.toolHandlers}},{conversationKey:k(),traces:g}),[e,v,s,g]),b=(0,q.useMemo)(()=>s?ee(e):void 0,[s,e]),x=ce({transport:y,iface:t,pageTools:b}),{sendText:S,handleStop:C}=x,w=(0,q.useRef)(x.phase);w.current=x.phase;let[T,E]=(0,q.useState)(0);(0,q.useEffect)(()=>{let e=!1,t=async()=>{for(;!e&&w.current===`streaming`;)await new Promise(e=>requestAnimationFrame(e))};return(async()=>{for(let n=T;n<a.turns.length;n+=1){if(await t(),e)return;if(w.current===`gated`)return v.startTurn(n-1),h({kind:`waiting`,turn:n});let{text:r,attachments:i}=a.turns[n];if(i>0)return h({kind:`missing`,turn:n});v.startTurn(n),h({kind:`running`,turn:n});try{let t=await S(r);if(e)return;if(p.current)return h({kind:`diverged`,divergence:p.current});t||--n}catch(e){let t=e instanceof Error?e.message:String(e);return h({kind:`failed`,turn:n,message:t})}}h({kind:`done`})})(),()=>{e=!0,C()}},[T,v,a,S,C]);let D=async t=>{f({...await Oe(e,d,a.turns.slice(0,t).flatMap(e=>e.blocks)),text:a.turns[t]?.text??``})},O=o===`replayed`;return(0,J.jsx)(X,{iface:t,feed:O?g:_,trace:n,card:r({isRunning:m.kind===`running`,onStop:()=>{C(),h({kind:`done`})}}),conversation:(0,J.jsx)(Z,{iface:t,blocks:O?[...x.blocks,...x.streamBlocks]:K(a),chat:O?x:void 0,banner:O?(0,J.jsx)(Ne,{status:m,turns:a.turns.length,onContinue:E,onLive:D}):void 0})})}function Fe(e){return(0,J.jsx)(m,{children:(0,J.jsx)(y,{labels:w,children:(0,J.jsx)(Ie,{...e})})})}function Ie({payload:e,trace:t,runtime:n,onLive:r,opened:i,onOpened:a,onClear:o}){let s=(0,q.useMemo)(()=>d(e),[e]),l=(0,q.useMemo)(()=>i&&be(i.records),[i]),u=(0,q.useMemo)(()=>c(i?.records??[]),[i]),[f,p]=(0,q.useState)(),[m,h]=(0,q.useState)(!1),g=f?.of===i&&f?.agent===e.profile.id?f:void 0,_=g?.attempt??0,v=g?.shown??`recorded`,y=e=>{g&&p({...g,shown:e})},b=()=>{i&&p({of:i,agent:e.profile.id,attempt:_+1,shown:`replayed`})};if(s.type===`live`)return null;if(!i||!l)return(0,J.jsx)(X,{iface:s,feed:u,trace:t,card:(0,J.jsx)($,{onImport:a}),conversation:null});let x=({isRunning:t,onStop:n})=>(0,J.jsx)($,{onImport:a,controls:{opened:i,script:l,payload:e,shown:_>0?v:null,onShown:y,liveTools:m,onLiveTools:e=>{h(e),_>0&&b()},isRunning:t,onReplay:b,onStop:n,onClear:o}});return _===0?(0,J.jsx)(X,{iface:s,feed:u,trace:t,card:x({isRunning:!1,onStop:()=>void 0}),conversation:(0,J.jsx)(Z,{iface:s,blocks:K(l)})}):(0,J.jsx)(Pe,{payload:e,iface:s,trace:t,card:x,opened:i,script:l,shown:v,liveTools:m,runtime:n,onLive:r},_)}export{Fe as TraceReplay};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{E as a,k as o}from"./browser-transport-LV_FgVKG.js";import{t as s}from"./Icon-BqkS-pIq.js";import{t as c}from"./Text-BOqCfzZC.js";import{n as l,o as u}from"./labels-provider-Bt3Q2GjB.js";import{n as d}from"./Card-DruykyeB.js";import{t as f}from"./IconButton-DVUFx-8p.js";import{t as p}from"./Tooltip-BWs5DLrM.js";import{d as m}from"./reader-D_UCUUJt.js";import{_ as h,b as g,g as _,y as v}from"./ConsoleFrame-DRsXYFYa.js";import{c as y,i as b}from"./trace-patterns-D6TbkLLr.js";import{t as x}from"./CardWall-Y542bbCc.js";import{R as S,T as C,V as w,w as T}from"./index-3PUx0L6S.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=d();return(0,E.useMemo)(()=>({percent:new Intl.NumberFormat(e,{style:`percent`,maximumFractionDigits:0}),decimal:new Intl.NumberFormat(e,{maximumFractionDigits:2}),usd:new Intl.NumberFormat(e,{style:`currency`,currency:`USD`,maximumSignificantDigits:2})}),[e])}function j(e){return y(e?`clear`:`shade2`)}function M({value:e,isLead:t}){return(0,D.jsx)(`div`,{style:{height:k,width:`${String(Math.max(e,.01)*100)}%`,borderRadius:4,background:j(t),transition:`width ${O}`}})}function N({title:e,aside:t,detail:n,answer:a}){let o=l(),s=A(),u=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a.choice,note:o(`@theorem.decision.confidence`,{percent:s.percent.format(a.confidence)}),children:(0,D.jsx)(r,{gap:2,role:`list`,children:u.map(([e,t])=>(0,D.jsxs)(r,{gap:1,role:`listitem`,"aria-label":o(`@theorem.decision.option`,{label:e,percent:s.percent.format(t)}),children:[(0,D.jsxs)(i,{gap:2,hAlign:`between`,"aria-hidden":!0,children:[(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(c,{type:`supporting`,hasTabularNumbers:!0,children:s.percent.format(t)})]}),(0,D.jsx)(M,{value:t,isLead:e===a.choice})]},e))})})}var P=56;function F(e){let t=e.split(/[:—–]\s/)[0]?.trim()??``;return t&&t.length<=32&&t!==e?t:e}function I({title:e,aside:t,detail:n,answer:i,labels:a}){let o=l(),s=A(),u=a.length,d=Math.min(u-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:a[d]===void 0?s.decimal.format(i.score):F(a[d]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(u-1)}),o(`@theorem.decision.confidence`,{percent:s.percent.format(i.confidence)})].join(` · `),children:(0,D.jsxs)(r,{gap:1,children:[(0,D.jsxs)(`div`,{"aria-hidden":!0,style:{position:`relative`,display:`flex`,alignItems:`flex-end`,gap:4,height:P},children:[a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,height:`${String(Math.max(.04,i.probabilities[String(t)]??0)*100)}%`,borderRadius:4,background:j(t===d),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/u*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,maxLines:1,children:F(e)})},`${String(t)}:${e}`))}),(0,D.jsx)(`span`,{style:{position:`absolute`,width:1,height:1,overflow:`hidden`,clipPath:`inset(50%)`},children:a.map((e,t)=>o(`@theorem.decision.option`,{label:e,percent:s.percent.format(i.probabilities[String(t)]??0)})).join(`; `)})]})})}function L({title:e,aside:t,detail:n,answer:r}){let i=A();return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:i.decimal.format(r.noul)})}var R=72,z=168;function B(e){let[t,n]=(0,E.useState)(null);return(0,E.useEffect)(()=>{let t=new Image;t.onload=()=>{n({width:t.naturalWidth,height:t.naturalHeight})},t.src=e},[e]),t}function V(e,t){let n=e.style.color;e.style.color=`var(${t})`;let r=getComputedStyle(e).color;return e.style.color=n,r}function H({source:e,box:t,caption:n}){let r=l(),i=v(e),a=B(i),[o,s]=(0,E.useState)(null);if(!a)return null;let c=h(t),u=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),d=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(p,{content:d,children:(0,D.jsx)(w,{label:d,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};g(i,t,n).then(s)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(u),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(c.width)}%`,height:`${String(c.height)}%`,left:`${String(c.left)}%`,top:`${String(c.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(S,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:{src:o??i,alt:r(`@theorem.decision.box_marked`),caption:n},hasZoom:!0})]})}function U({title:e,aside:t,detail:n,answer:r,image:i,asked:a}){let o=l(),s=a&&_(a.images,a.state,i),c=A(),{top:u,bottom:d,left:f,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(f),top:c.percent.format(u),right:c.percent.format(p),bottom:c.percent.format(d)});return(0,D.jsx)(b,{title:e,aside:t,detail:n,value:m,note:o(`@theorem.decision.confidence`,{percent:c.percent.format(r.confidence)}),children:s?(0,D.jsx)(H,{source:s,box:r.box,caption:`${e}: ${m}`}):(0,D.jsx)(`div`,{"aria-hidden":!0,style:{position:`relative`,height:R,borderRadius:4,border:`1px solid var(--color-border)`},children:(0,D.jsx)(`div`,{style:{position:`absolute`,insetInlineStart:`${String(f*100)}%`,insetBlockStart:`${String(u*100)}%`,width:`${String((p-f)*100)}%`,height:`${String((d-u)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let a=l(),c=`${e.id} · ${a(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let u=a(`@theorem.decision.edit_question`,{question:e.id}),d={title:c,detail:i,aside:r?(0,D.jsx)(f,{label:u,tooltip:u,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(s,{icon:o,size:`xsm`,color:`secondary`}),onClick:()=>{r(e.id)}}):void 0};return t.type===`choice`?(0,D.jsx)(N,{...d,answer:t}):t.type===`score`?(0,D.jsx)(I,{...d,answer:t,labels:e.labels}):t.type===`noul`?(0,D.jsx)(L,{...d,answer:t}):(0,D.jsx)(U,{...d,answer:t,image:e.image,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=l(),d=A();return(0,D.jsx)(C,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(T,{children:(0,D.jsx)(c,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:u(s,d.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=l();return(0,D.jsx)(G,{model:t.model,usage:t.usage,elapsedMs:n,isStale:r,tokens:e=>s(`@theorem.decision.tokens`,{count:e}),children:(0,D.jsx)(x,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(T,{children:(0,D.jsx)(W,{question:e,answer:t.answers[e.id],asked:i,onQuestion:a,detail:o?.[e.id]})},e.id))})})}var q={status:`idle`,result:null,elapsedMs:null,startedAt:null,failure:null};function J(e,t){for(let n of t??[])e.traces?.push(n)}function Y(e,t,n){let[r,i]=(0,E.useState)(q),o=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>o.current?.abort(),[]);let s=(0,E.useCallback)(()=>{o.current?.abort(),o.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{o.current?.abort();let s=new AbortController;o.current=s,i(e=>({status:t,result:e.result,elapsedMs:e.elapsedMs,startedAt:Date.now(),failure:null}));let c=performance.now();try{let t=await n(e,s.signal,...r);if(s.signal.aborted)return;J(e,t.traces),i({status:`done`,result:t.result,elapsedMs:performance.now()-c,startedAt:null,failure:null})}catch(t){if(s.signal.aborted)return;J(e,m(t)),i(e=>({...e,status:`error`,startedAt:null,failure:a(t)}))}finally{o.current===s&&(o.current=null)}},[e,t,n]);return{...r,call:c,cancel:s}}export{A as a,K as i,G as n,M as r,Y as t};
package/page/index.html CHANGED
@@ -10,7 +10,7 @@
10
10
  href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%23000'/%3E%3Cg transform='translate(4 4)' fill='none' stroke='%23fff' stroke-width='2' stroke-linecap='round'%3E%3Cpath d='M4.5 18.5c2 0 3-1.2 4.2-3.4l2.6-5c1-1.9 2.1-3.1 4.2-3.1'/%3E%3Cpath d='M5.5 8.2c1.6-.9 3.2-.4 3.8 1.6l2.3 6.6c.6 1.7 2.1 2.4 3.9 1.7'/%3E%3Ccircle cx='19.5' cy='4.5' r='1.6' fill='%23fff' stroke='none'/%3E%3C/g%3E%3C/svg%3E"
11
11
  />
12
12
  <title>theorem studio</title>
13
- <script type="module" crossorigin src="/studio/assets/index-Dblg49i6.js"></script>
13
+ <script type="module" crossorigin src="/studio/assets/index-3PUx0L6S.js"></script>
14
14
  <link rel="modulepreload" crossorigin href="/studio/assets/rolldown-runtime-hePW80VL.js">
15
15
  <link rel="modulepreload" crossorigin href="/studio/assets/themeProps-3IqahpCr.js">
16
16
  <link rel="modulepreload" crossorigin href="/studio/assets/tokens.stylex-DkHf0P9C.js">
@@ -54,14 +54,14 @@
54
54
  <link rel="modulepreload" crossorigin href="/studio/assets/tree-DfG6CXsC.js">
55
55
  <link rel="modulepreload" crossorigin href="/studio/assets/browser-connection-pM-ZbsQr.js">
56
56
  <link rel="modulepreload" crossorigin href="/studio/assets/use-second-ticker-BSCE_-wM.js">
57
- <link rel="modulepreload" crossorigin href="/studio/assets/Banner-DjmNbolt.js">
58
- <link rel="modulepreload" crossorigin href="/studio/assets/arrive-DvbqpeRS.js">
57
+ <link rel="modulepreload" crossorigin href="/studio/assets/Banner-DNuB7lhC.js">
58
+ <link rel="modulepreload" crossorigin href="/studio/assets/row-keys-WByP9Hsh.js">
59
59
  <link rel="modulepreload" crossorigin href="/studio/assets/Center-nHS1JSux.js">
60
60
  <link rel="modulepreload" crossorigin href="/studio/assets/IconSearch-BTx66a40.js">
61
61
  <link rel="modulepreload" crossorigin href="/studio/assets/trace-schema-9CdEyG6Q.js">
62
62
  <link rel="modulepreload" crossorigin href="/studio/assets/stub-DSUcPMOV.js">
63
63
  <link rel="modulepreload" crossorigin href="/studio/assets/reader-D_UCUUJt.js">
64
- <link rel="modulepreload" crossorigin href="/studio/assets/browser-transport-BgmUaqDP.js">
64
+ <link rel="modulepreload" crossorigin href="/studio/assets/browser-transport-LV_FgVKG.js">
65
65
  <link rel="modulepreload" crossorigin href="/studio/assets/focusReturn-CTppP2k0.js">
66
66
  <link rel="modulepreload" crossorigin href="/studio/assets/CheckboxInput-CFZ_Wq8-.js">
67
67
  <link rel="modulepreload" crossorigin href="/studio/assets/useScrollLock-Dyf6PHJt.js">
@@ -74,7 +74,7 @@
74
74
  <link rel="modulepreload" crossorigin href="/studio/assets/encode-files-DxWGM2XV.js">
75
75
  <link rel="modulepreload" crossorigin href="/studio/assets/turn-client-CZG4gVtX.js">
76
76
  <link rel="modulepreload" crossorigin href="/studio/assets/CollapsibleGroup-FIawJRo4.js">
77
- <link rel="modulepreload" crossorigin href="/studio/assets/studio-labels-CGR8sQpd.js">
77
+ <link rel="modulepreload" crossorigin href="/studio/assets/studio-labels-7sgmTzU-.js">
78
78
  <link rel="modulepreload" crossorigin href="/studio/assets/crypto-CY8dSBJ4.js">
79
79
  <link rel="modulepreload" crossorigin href="/studio/assets/workspace-CzTPlUdi.js">
80
80
  <link rel="modulepreload" crossorigin href="/studio/assets/lent-keys-C32ems-I.js">
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i,t as a}from"./StackItem-CQviqAfM.js";var o=e(n(),1);function s(e,t,n){return Math.max(1,Math.floor((e+n)/(t+n)))}function c(e,t,n){let r=Array.from({length:t},()=>[]),i=Array.from({length:t},()=>0);return e.forEach((e,t)=>{let a=i.indexOf(Math.min(...i));r[a]?.push(t),i[a]=(i[a]??0)+(e??0)+n}),r}var l=t();function u(e,t,n,r){let i=Array.from({length:r});n.forEach((e,n)=>{let r=t[n]?.children;e.forEach((e,t)=>{let n=r?.[t];n instanceof HTMLElement&&(i[e]=n.offsetHeight)})});let a=Number.parseFloat(getComputedStyle(e).columnGap)||0;return{width:e.clientWidth,gap:a,heights:i}}function d(e,t){return e.width===t.width&&e.gap===t.gap&&e.heights.length===t.heights.length&&e.heights.every((e,n)=>e===t.heights[n])}function f({minWidth:e,children:t}){let n=o.Children.toArray(t),f=(0,o.useRef)(null),p=(0,o.useRef)([]),[m,h]=(0,o.useState)({width:0,gap:0,heights:[]}),g=c(n.map((e,t)=>m.heights[t]),s(m.width,e,m.gap),m.gap),_=(0,o.useRef)(g);_.current=g;let v=g.map(e=>e.join(` `)).join(`|`);return(0,o.useLayoutEffect)(()=>{let e=f.current;if(!e||!v)return;let t=()=>{let t=u(e,p.current,_.current,n.length);h(e=>d(e,t)?e:t)};t();let r=new ResizeObserver(t);r.observe(e);for(let e of p.current)for(let t of e?.children??[])r.observe(t);return()=>r.disconnect()},[v,n.length]),(0,l.jsx)(i,{ref:f,gap:3,vAlign:`start`,children:g.map((e,t)=>(0,l.jsx)(a,{size:`fill`,children:(0,l.jsx)(r,{ref:e=>{p.current[t]=e},gap:3,children:e.map(e=>n[e])})},String(t)))})}export{f as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{n as r,t as i}from"./SegmentedControlItem-BBGRPrxp.js";import{t as a}from"./VStack-CkVMcNiK.js";import{n as o,t as s}from"./StackItem-CQviqAfM.js";import{t as c}from"./DateInput-B1ICJtHn.js";import{t as l}from"./Text-BOqCfzZC.js";import{n as u}from"./labels-provider-Bt3Q2GjB.js";import{n as d}from"./ScrollableArea-BHfY7sWH.js";import{a as f}from"./arrive-DvbqpeRS.js";import{c as p,d as m,f as h}from"./tool-schema-CPVHlZ7w.js";import{c as g,l as _}from"./shaped-data-C4yaGRz9.js";import{c as v,d as y,l as b,u as x}from"./ConsoleFrame-DA11Fku_.js";import{E as S,N as C,P as w,V as T,d as E,f as D,w as O,x as k,y as A}from"./index-Dblg49i6.js";var j=e(n(),1),M=t(),N={search:()=>[],bootstrap:()=>[]},P={"--font-family-body":`var(--font-family-code)`},F=2;function I({text:e}){return(0,M.jsx)(l,{type:`supporting`,color:`secondary`,maxLines:F,children:e})}function L({field:e,children:t}){return(0,M.jsx)(x,{label:e.label,isRequired:e.isRequired,children:t})}function R({field:e,value:t,onChange:n}){let r=u(),[i,a]=(0,j.useState)(()=>t===void 0?``:_(t)),[o,s]=(0,j.useState)(!0);return(0,M.jsx)(k,{label:e.label,isRequired:e.isRequired,size:`sm`,rows:3,value:i,hasSpellCheck:!1,status:o?void 0:{type:`error`,message:r(`@theorem.decision.invalid_json`)},controlStyle:P,onChange:e=>{if(a(e),e.trim()===``)s(!0),n(void 0);else try{n(JSON.parse(e)),s(!0)}catch{s(!1)}}})}function z({field:e,item:t,value:n,onChange:r}){let i=Array.isArray(n)?n:[],c=f(i);return(0,M.jsx)(b,{label:e.label,isRequired:e.isRequired,description:e.description&&(0,M.jsx)(I,{text:e.description}),children:(0,M.jsxs)(a,{gap:3,children:[c.rows.map(({item:e,index:n,key:a})=>(0,M.jsxs)(o,{gap:2,vAlign:`start`,children:[(0,M.jsx)(s,{size:`fill`,children:(0,M.jsx)(Y,{schema:t,value:g(e)?e:{},onChange:e=>r(i.map((t,r)=>r===n?e:t))})}),(0,M.jsx)(y,{index:n,onRemove:()=>{c.drop(n),r(i.filter((e,t)=>t!==n))}})]},a)),(0,M.jsx)(v,{field:e.label,onAdd:()=>r([...i,p(t)])})]})})}function B(e){return{label:e.label,isRequired:e.isRequired,size:`sm`}}function V({field:e,options:t,isMenu:n,value:a,onChange:s}){return n?(0,M.jsx)(T,{...B(e),options:t,value:typeof a==`string`?a:void 0,hasSearch:t.length>10,onChange:s}):(0,M.jsx)(L,{field:e,children:(0,M.jsx)(o,{children:(0,M.jsx)(r,{label:e.label,size:`sm`,value:typeof a==`string`?a:``,onChange:s,children:t.map(e=>(0,M.jsx)(i,{value:e,label:e},e))})})})}function H({field:e,isLong:t,type:n,value:r,onChange:i}){let a=typeof r==`string`?r:``;return t?(0,M.jsx)(k,{...B(e),rows:3,value:a,onChange:i}):(0,M.jsx)(d,{...B(e),type:n,value:a,onChange:i})}function U({field:e,value:t,onChange:n}){let r=u(),i=Array.isArray(t)?t:[];return(0,M.jsx)(O,{...B(e),value:i.map((e,t)=>({id:`${String(t)}:${String(e)}`,label:String(e)})),searchSource:N,hasCreate:!0,debounceMs:0,placeholder:r(`@theorem.decision.add_value`),onChange:e=>n(e.map(e=>typeof i[0]==`number`&&Number.isFinite(Number(e.label))?Number(e.label):e.label))})}var W={choice:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(V,{field:e,options:t.options,isMenu:t.isMenu,value:n,onChange:r}),range:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(E,{label:e.label,isRequired:e.isRequired,min:t.min,max:t.max,step:1,value:typeof n==`number`?n:t.min,valueDisplay:`text`,onChange:r}),number:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(S,{...B(e),value:typeof n==`number`?n:void 0,min:t.min,max:t.max,isIntegerOnly:t.isInteger,isWheelEnabled:!1,onChange:e=>r(e??void 0)}),switch:({field:e,value:t,onChange:n})=>(0,M.jsx)(A,{label:e.label,value:t===!0,onChange:n}),date:({field:e,value:t,onChange:n})=>(0,M.jsx)(c,{...B(e),value:typeof t==`string`?t:void 0,onChange:n}),text:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(H,{field:e,isLong:t.isLong,type:t.type,value:n,onChange:r}),choices:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(w,{label:e.label,value:Array.isArray(n)?n.filter(e=>typeof e==`string`):[],onChange:r,children:t.options.map(e=>(0,M.jsx)(C,{label:e,value:e},e))}),words:({field:e,value:t,onChange:n})=>(0,M.jsx)(U,{field:e,value:t,onChange:n}),rows:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(z,{field:e,item:t.item,value:n,onChange:r}),group:({field:e,control:t,value:n,onChange:r})=>(0,M.jsx)(b,{label:e.label,isRequired:e.isRequired,description:e.description&&(0,M.jsx)(I,{text:e.description}),children:(0,M.jsx)(Y,{schema:t.schema,value:g(n)?n:{},onChange:r})}),json:({field:e,value:t,onChange:n})=>(0,M.jsx)(R,{field:e,value:t,onChange:n})};function G({field:e,value:t,onChange:n}){let r=W[e.control.kind],i=r({field:e,control:e.control,value:t,onChange:n}),o=e.control.kind===`rows`||e.control.kind===`group`;return!e.description||o?i:(0,M.jsxs)(a,{gap:1,children:[i,(0,M.jsx)(I,{text:e.description})]})}var K=200,q=18;function J({control:e}){switch(e.kind){case`number`:case`switch`:case`date`:return!0;case`choice`:return e.isMenu||e.options.join(``).length<=q;case`text`:return!e.isLong;default:return!1}}function Y({schema:e,value:t,onChange:n}){return(0,M.jsx)(D,{columns:{minWidth:K,repeat:`fill`},gap:3,children:m(e).map(e=>(0,M.jsx)(`div`,{style:J(e)?{minWidth:0,alignSelf:`start`}:{gridColumn:`1 / -1`,minWidth:0},children:(0,M.jsx)(G,{field:e,value:t[e.key],onChange:r=>n(h(t,e.key,r))})},e.key))})}function X({schema:e,value:t,onChange:n}){return(0,M.jsx)(Y,{schema:e,value:t,onChange:n})}export{X as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./VStack-CkVMcNiK.js";import{n as i}from"./StackItem-CQviqAfM.js";import{t as a}from"./Text-BOqCfzZC.js";import{n as o}from"./Card-DruykyeB.js";import{t as s}from"./arrive-DvbqpeRS.js";import{x as c}from"./shaped-data-C4yaGRz9.js";import{$ as l,B as u,Ct as d,Et as f,F as p,H as m,Ht as h,I as g,It as _,Jt as v,M as y,Mt as b,N as x,Nt as S,P as C,Q as ee,Qt as w,Ut as T,V as te,Vt as E,X as ne,Y as re,Yt as ie,Z as ae,_t as oe,an as D,at as se,cn as ce,ct as le,dn as ue,dt as de,en as fe,fn as pe,gt as me,ht as O,jt as he,kt as ge,ln as _e,lt as ve,mt as ye,n as be,nn as k,nt as xe,ot as Se,pn as Ce,qt as A,st as we,t as j,tn as M,tt as Te,un as Ee,ut as De,wt as Oe,xt as N,z as ke,zt as P}from"./TraceOverview-BitZyKPI.js";import{a as Ae,c as F,i as I,s as L}from"./trace-patterns-D6TbkLLr.js";import{t as je}from"./CardWall-CBRLdDZW.js";import{n as Me}from"./studio-host-console-TXtb6kyY.js";var R=e(n()),Ne=[`animationElapsedTime`,`isAnimating`,`isEntrance`,`visibleLength`,`strokeDasharray`,`connectNulls`];function z(){return z=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},z.apply(null,arguments)}function Pe(e,t){if(e==null)return{};var n,r,i=Fe(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Fe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Ie(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function B(e,t){return`${t}px ${e}px`}function Le(e){return e.length%2==0?e:[...e,...e]}function Re(e,t){for(var n=[],r=0;r<t;++r)n.push(...e);return n}function ze(e,t,n){var r=Le(n),i=r.reduce((e,t)=>e+t,0);if(!i)return B(t,e);for(var a=Math.floor(e/i),o=e%i,s=[],c=0,l=0;c<r.length;l+=(u=r[c])??0,++c){var u,d=r[c];if(d!=null&&l+d>o){s=[...r.slice(0,c),o-l];break}}var f=s.length%2==0?[0,t]:[t];return[...Re(r,a),...s,...f].map(e=>`${e}px`).join(`, `)}function Be(e,t,n){return e?ze(n,t,`${e}`.split(/[,\s]+/gim).map(e=>parseFloat(e))):B(t,n)}function Ve(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,i=Pe(e,Ne),a=r??!1,o;if(t!=null){var s=i.pathRef;o=Be(n,Ie(s?.current??null),t)}else n!=null&&(o=String(n));return R.createElement(he,z({},i,{connectNulls:a,strokeDasharray:o}))}function He(e){var t=(0,R.useRef)(0),n=(0,R.useRef)(0),r=(0,R.useRef)(!1),i=(0,R.useRef)(e);return i.current!==e&&(t.current=n.current,i.current=e),(0,R.useCallback)((e,i)=>{if(r.current)return null;var a=Math.min(_e(t.current+e*i),i);return e>0&&i>0&&(n.current=Math.max(n.current,a),a>=i)?(r.current=!0,null):a},[])}var V=(e,t,n,r)=>N(e,`xAxis`,t,r),H=(e,t,n,r)=>d(e,`xAxis`,t,r),U=(e,t,n,r)=>N(e,`yAxis`,n,r),W=(e,t,n,r)=>d(e,`yAxis`,n,r),Ue=w([S,V,U,H,W],(e,t,n,r,i)=>ie(e,`xAxis`)?h(t,r,!1):h(n,i,!1)),We=(e,t,n,r,i)=>i;function Ge(e){return e.type===`line`}var Ke=w([Oe,We],(e,t)=>e.filter(Ge).find(e=>e.id===t)),qe=w([S,V,U,H,W,Ke,Ue,ge],(e,t,n,r,i,a,o,s)=>{var c=s.chartData,l=s.dataStartIndex,u=s.dataEndIndex;if(!(a==null||t==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||e!==`horizontal`&&e!==`vertical`)){var d=a.dataKey,f=a.data,p=f!=null&&f.length>0?f:c?.slice(l,u+1);if(p!=null)return pt({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:d,bandSize:o,displayedData:p})}}),Je=[`id`],Ye=[`type`,`layout`,`connectNulls`,`needClip`,`shape`,`strokeDasharray`],Xe=[`activeDot`,`animateNewValues`,`animationBegin`,`animationDuration`,`animationEasing`,`connectNulls`,`dot`,`hide`,`isAnimationActive`,`label`,`legendType`,`xAxisId`,`yAxisId`,`id`];function G(){return G=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},G.apply(null,arguments)}function K(e,t){if(e==null)return{};var n,r,i=Ze(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ze(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function q(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function J(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?q(Object(n),!0).forEach(function(t){Qe(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):q(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Qe(e,t,n){return(t=$e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $e(e){var t=et(e,`string`);return typeof t==`symbol`?t:t+``}function et(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function tt(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function nt(e){var t=0,n=0;for(var r of e)r.status===`matched`&&r.prev.x!=null&&r.next.x!=null&&(t+=r.next.x-r.prev.x,n++);return n>0?t/n:0}var Y={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:`ease`,animationInterpolateFn:(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(e=>e.status===`removed`?[]:[e.next]);var n=nt(e),r=[];for(var i of e)if(i.status===`matched`)r.push(J(J({},i.next),{},{x:k(i.prev.x,i.next.x,t),y:k(i.prev.y,i.next.y,t)}));else if(i.status===`added`){if(i.next.x!=null){var a=i.next.x-n;r.push(J(J({},i.next),{},{x:k(a,i.next.x,t),y:i.next.y}))}else r.push(i.next)}else if(i.status===`removed`&&i.prev.x!=null){var o=i.prev.x+n;r.push(J(J({},i.prev),{},{x:k(i.prev.x,o,t),y:i.prev.y}))}return r},animationMatchBy:se,connectNulls:!1,dot:!0,fill:`#fff`,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`line`,shape:Ve,stroke:`#3182bd`,strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:f.line,type:`linear`},rt=e=>{var t=e.dataKey,n=e.name,r=e.stroke,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:A(n,t),payload:e}]},it=R.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,i=e.strokeWidth,a=e.fill,o=e.name,s=e.hide,c=e.unit,l=e.formatter,u=e.tooltipType,d=e.id,f={dataDefinedOnItem:n,getPosition:ce,settings:{stroke:r,strokeWidth:i,fill:a,dataKey:t,nameKey:void 0,name:A(o,t),hide:s,type:u,color:r,unit:c,formatter:l,graphicalItemId:d}};return R.createElement(we,{tooltipEntrySettings:f})});function at(e){var t=e.clipPathId,n=e.points,r=e.props,i=r.dot,a=r.dataKey,o=r.needClip;r.id;var s=K(r,Je),c=pe(s);return R.createElement(ae,{points:n,dot:i,className:`recharts-line-dots`,dotClassName:`recharts-line-dot`,dataKey:a,baseProps:c,needClip:o,clipPathId:t})}function ot(e){var t=e.showLabels,n=e.children,r=e.points,i=(0,R.useMemo)(()=>r?.map(e=>{var t={x:e.x??0,y:e.y??0,width:0,lowerWidth:0,upperWidth:0,height:0};return J(J({},t),{},{value:e.value,payload:e.payload,viewBox:t,parentViewBox:void 0,fill:void 0})}),[r]);return R.createElement(De,{value:t?i:void 0},n)}function st(e){var t=e.clipPathId,n=e.pathRef,r=e.points,i=e.props,a=e.animationElapsedTime,o=e.isAnimating,s=e.isEntrance,c=e.visibleLength,l=i.type,u=i.layout,d=i.connectNulls,f=i.needClip,p=i.shape,m=i.strokeDasharray,h=K(i,Ye),g=J(J({},ue(h)),{},{fill:`none`,className:`recharts-line-curve`,clipPath:f?`url(#clipPath-${t})`:void 0,points:r,type:l,layout:u,connectNulls:d,strokeDasharray:m??i.strokeDasharray,pathRef:n,animationElapsedTime:a,isAnimating:o,isEntrance:i.animateNewValues?s:!1,visibleLength:c});return R.createElement(R.Fragment,null,r?.length>1&&R.createElement(le,{option:p,DefaultShape:Y.shape,shapeProps:g}),R.createElement(at,{points:r,clipPathId:t,props:i}))}function ct(e){var t=e.clipPathId,n=e.props,r=e.pathRef,i=e.previousPointsRef,a=n.points,o=n.isAnimationActive,s=n.animationBegin,c=n.animationDuration,l=n.animationEasing,u=n.animationMatchBy,d=n.animationInterpolateFn,f=n.layout,p=tt(r.current),m=xe(n.onAnimationStart,n.onAnimationEnd),h=m.isAnimating,g=m.handleAnimationStart,_=m.handleAnimationEnd,v=!h,y=He(a),b=(0,R.useCallback)(e=>e>0&&p>0,[p]);return R.createElement(ot,{points:a,showLabels:v},n.children,R.createElement(Te,{animationInput:a,animationIdPrefix:`recharts-line-`,items:a,previousItemsRef:i,isAnimationActive:o,animationBegin:s,animationDuration:c,animationEasing:l,onAnimationStart:g,onAnimationEnd:_,animationInterpolateFn:d,animationMatchBy:u,shouldUpdatePreviousRef:b,layout:f},(e,i,a)=>{var o=h||i<1,s=o?y(i,p):null;return R.createElement(st,{props:n,points:e,clipPathId:t,pathRef:r,animationElapsedTime:i,isAnimating:o,isEntrance:a,visibleLength:s})}),R.createElement(de,{label:n.label}))}function lt(e){var t=e.clipPathId,n=e.props,r=(0,R.useRef)(null),i=(0,R.useRef)(null);return R.createElement(ct,{props:n,clipPathId:t,previousPointsRef:r,pathRef:i})}var ut=(e,t)=>({x:e.x??void 0,y:e.y??void 0,value:e.value,errorVal:v(e.payload,t)}),dt=class extends R.Component{render(){var e=this.props,t=e.hide,n=e.dot,r=e.points,i=e.className,a=e.xAxisId,o=e.yAxisId,s=e.top,c=e.left,l=e.width,d=e.height,f=e.id,p=e.needClip,h=e.zIndex;if(t)return null;var g=Ce(`recharts-line`,i),_=f,v=ke(n),y=v.r,b=v.strokeWidth,x=ve(n),S=y*2+b,C=p?`url(#clipPath-${x?``:`dots-`}${_})`:void 0;return R.createElement(oe,{zIndex:h},R.createElement(Ee,{className:g},p&&R.createElement(`defs`,null,R.createElement(u,{clipPathId:_,xAxisId:a,yAxisId:o}),!x&&R.createElement(`clipPath`,{id:`clipPath-dots-${_}`},R.createElement(`rect`,{x:c-S/2,y:s-S/2,width:l+S,height:d+S}))),R.createElement(m,{xAxisId:a,yAxisId:o,data:r,dataPointFormatter:ut,errorBarOffset:0},R.createElement(lt,{props:this.props,clipPathId:_}))),R.createElement(re,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:C}))}};function ft(e){var t=M(e,Y),n=t.activeDot,r=t.animateNewValues,i=t.animationBegin,a=t.animationDuration,o=t.animationEasing,s=t.connectNulls,c=t.dot,l=t.hide,u=t.isAnimationActive,d=t.label,f=t.legendType,p=t.xAxisId,m=t.yAxisId,h=t.id,g=K(t,Xe),v=te(p,m).needClip,y=ne(),b=_(),x=E(),S=fe(e=>qe(e,p,m,x,h));if(b!==`horizontal`&&b!==`vertical`||S==null||y==null)return null;var C=y.height,ee=y.width,w=y.x,T=y.y;return R.createElement(dt,G({},g,{id:h,connectNulls:s,dot:c,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:a,animationEasing:o,isAnimationActive:u,hide:l,label:d,legendType:f,xAxisId:p,yAxisId:m,points:S,layout:b,height:C,width:ee,left:w,top:T,needClip:v}))}function pt(e){var t=e.layout,n=e.xAxis,r=e.yAxis,i=e.xAxisTicks,a=e.yAxisTicks,o=e.dataKey,s=e.bandSize;return e.displayedData.map((e,c)=>{var l=v(e,o);if(t===`horizontal`)return{x:T({axis:n,ticks:i,bandSize:s,entry:e,index:c}),y:(D(l)?null:r.scale.map(l))??null,value:l,payload:e};var u=D(l)?null:n.scale.map(l),d=T({axis:r,ticks:a,bandSize:s,entry:e,index:c});return u==null||d==null?null:{x:u,y:d,value:l,payload:e}}).filter(Boolean)}function mt(e){var t=M(e,Y),n=E();return R.createElement(l,{id:t.id,type:`line`},e=>R.createElement(R.Fragment,null,R.createElement(Se,{legendPayload:rt(t)}),R.createElement(it,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),R.createElement(ee,{type:`line`,id:e,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),R.createElement(ft,G({},t,{id:e}))))}var X=R.memo(mt,b);X.displayName=`Line`;var ht=[`axis`],gt=(0,R.forwardRef)((e,t)=>R.createElement(x,{chartName:`LineChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:ht,tooltipPayloadSearcher:me,categoricalChartProps:e,ref:t})),Z=t(),_t=140,vt=22,Q={fill:`var(--color-text-secondary)`,fontSize:11},yt={radius:4,stroke:Ae,strokeWidth:2,isAnimationActive:!1},$=[`clear`,`shade1`,`shade2`];function bt(e){let t=o();return(0,R.useMemo)(()=>{let n=new Intl.NumberFormat(t,{maximumFractionDigits:2}),r=(e,t)=>c(n.format(e),t),i=e.kind===`time`?e.rows.map(t=>String(t[e.x])):[],a=Me(i),o=new Intl.DateTimeFormat(t,a.tick),s=new Intl.DateTimeFormat(t,a.when),l=e=>t=>{let n=Date.parse(t);return Number.isNaN(n)?t:e.format(n)};return{number:r,tick:l(o),when:l(s)}},[e,t])}function xt({active:e,payload:t,label:n,chart:o,formats:s}){return!e||!t?.length?null:(0,Z.jsx)(be,{children:(0,Z.jsxs)(r,{gap:0,children:[(0,Z.jsx)(a,{weight:`medium`,children:s.when(String(n))}),o.series.map((e,n)=>{let r=t.find(t=>t.dataKey===e.key)?.value;return typeof r==`number`?(0,Z.jsxs)(i,{gap:2,vAlign:`center`,children:[o.series.length>1?(0,Z.jsx)(L,{fill:$[n]??`clear`}):null,(0,Z.jsxs)(a,{type:`supporting`,hasTabularNumbers:!0,children:[o.series.length>1?`${e.label} `:``,s.number(r,e.unit)]})]},e.key):null})]})})}function St({chart:e}){let t=bt(e),[n]=e.series,r=e.series.flatMap(t=>e.rows.map(e=>e[t.key]).filter(e=>typeof e==`number`)),o=n?e.rows.map(e=>e[n.key]).find(e=>typeof e==`number`):void 0;if(!n||o===void 0)return null;let s=n.unit,c=`${t.number(Math.min(...r))}–${t.number(Math.max(...r),s)}`;return(0,Z.jsxs)(I,{title:e.title,value:t.number(o,s),note:c,children:[(0,Z.jsx)(j,{children:(0,Z.jsx)(P,{width:`100%`,height:_t,initialDimension:{width:280,height:_t},children:(0,Z.jsxs)(gt,{data:e.rows,margin:{top:4,right:4,bottom:0,left:0},accessibilityLayer:!1,children:[(0,Z.jsx)(p,{dataKey:e.x,tick:Q,tickLine:!1,axisLine:!1,tickFormatter:t.tick,minTickGap:16}),(0,Z.jsx)(C,{tick:Q,tickLine:!1,axisLine:!1,width:36,domain:[`auto`,`auto`],tickFormatter:e=>t.number(e)}),(0,Z.jsx)(O,{content:n=>(0,Z.jsx)(xt,{...n,chart:e,formats:t}),cursor:{stroke:`var(--color-border-emphasized)`},isAnimationActive:!1}),e.series.map((e,t)=>(0,Z.jsx)(X,{type:`monotone`,dataKey:e.key,stroke:F($[t]??`clear`),strokeWidth:2,dot:!1,activeDot:{r:3,strokeWidth:0},connectNulls:!0,isAnimationActive:!1},e.key))]})})}),e.series.length>1?(0,Z.jsx)(i,{gap:3,wrap:`wrap`,children:e.series.map((e,t)=>(0,Z.jsxs)(i,{gap:2,vAlign:`center`,children:[(0,Z.jsx)(L,{fill:$[t]??`clear`}),(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,children:e.label})]},e.key))}):null]})}function Ct({active:e,payload:t,chart:n,formats:i}){let o=t?.[0]?.payload;return!e||!o?null:(0,Z.jsx)(be,{children:(0,Z.jsxs)(r,{gap:0,children:[(0,Z.jsx)(a,{weight:`medium`,children:o.label}),(0,Z.jsx)(a,{type:`supporting`,hasTabularNumbers:!0,children:i.number(o.value,n.series.unit)})]})})}function wt({chart:e}){let t=bt(e),n=(0,R.useMemo)(()=>e.rows.map((e,t)=>({...e,id:String(t)})),[e]),[r]=n;if(!r)return null;let i=n.length*vt;return(0,Z.jsx)(I,{title:e.title,value:t.number(r.value,e.series.unit),note:r.label,children:(0,Z.jsx)(j,{children:(0,Z.jsx)(P,{width:`100%`,height:i,initialDimension:{width:280,height:i},children:(0,Z.jsxs)(y,{data:n,layout:`vertical`,margin:{top:0,right:56,bottom:0,left:0},accessibilityLayer:!1,barCategoryGap:5,children:[(0,Z.jsx)(p,{type:`number`,hide:!0}),(0,Z.jsx)(C,{type:`category`,dataKey:`id`,width:104,tick:Q,tickLine:!1,axisLine:!1,interval:0,tickFormatter:e=>{let t=n[Number(e)]?.label??``;return t.length>15?`${t.slice(0,14)}…`:t}}),(0,Z.jsx)(O,{content:n=>(0,Z.jsx)(Ct,{...n,chart:e,formats:t}),cursor:{fill:`var(--color-overlay-hover)`,radius:4},isAnimationActive:!1}),(0,Z.jsx)(g,{dataKey:`value`,...yt,label:{position:`right`,fill:`var(--color-text-secondary)`,fontSize:11,formatter:n=>t.number(Number(n),e.series.unit)},children:n.map((e,t)=>(0,Z.jsx)(ye,{fill:F(t===0?`clear`:`shade2`)},e.id))})]})})})})}function Tt({charts:e}){return(0,Z.jsx)(je,{minWidth:260,children:e.map(e=>(0,Z.jsx)(s,{children:e.kind===`time`?(0,Z.jsx)(St,{chart:e}):(0,Z.jsx)(wt,{chart:e})},e.key))})}export{Tt as ToolResultCharts};