@theoremjs/studio 0.3.4-next.385.ga3608be → 0.3.4-next.387.g8bea7ff

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 (27) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{Banner-DgPjY5Yu.js → Banner-D2s9xjDu.js} +2 -2
  3. package/page/assets/{ContextMenu-B-dMscLp.js → ContextMenu-Bs-xBzLA.js} +2 -2
  4. package/page/assets/{ToolResultCharts-oLH6ynx0.js → ToolResultCharts-DP6XvRai.js} +1 -1
  5. package/page/assets/{TraceInspector-DjRGsfQ6.js → TraceInspector-DmrYVbB9.js} +1 -1
  6. package/page/assets/{TraceOverview-CJJg8bUz.js → TraceOverview-BH5UvvAW.js} +1 -1
  7. package/page/assets/{browser-engine-BwN7Ib6D.js → browser-engine-Dduo9AOi.js} +1 -1
  8. package/page/assets/{browser-transport-CidXgImE.js → browser-transport-KwpVG2px.js} +3 -3
  9. package/page/assets/{export-agent-B0mZ4wL6.js → export-agent-BeBzFZ7T.js} +1 -1
  10. package/page/assets/{guardrail-tester-C-iVoY5f.js → guardrail-tester-BHQjkUP-.js} +1 -1
  11. package/page/assets/{index-D7CjWX1v.js → index-C_weLbPu.js} +7 -6
  12. package/page/assets/index-Oo9otEIT.css +1 -0
  13. package/page/assets/{studio-code-pane-DDPb5n7P.js → studio-code-pane-Culehk_a.js} +1 -1
  14. package/page/assets/{studio-console-D59tIXKj.js → studio-console-CawD8qZ8.js} +1 -1
  15. package/page/assets/{studio-decision-CoJDXc1v.js → studio-decision-DdqYtp4p.js} +1 -1
  16. package/page/assets/{studio-embedding-de6dCLXd.js → studio-embedding-B9Gsa6Fd.js} +1 -1
  17. package/page/assets/{studio-host-console-DTu-WVSS.js → studio-host-console-CDJllabB.js} +2 -2
  18. package/page/assets/{studio-live-DCvAJAO5.js → studio-live-Bt1dF-IZ.js} +1 -1
  19. package/page/assets/{studio-map-DOSqlz_M.js → studio-map-3VNh8RBZ.js} +1 -1
  20. package/page/assets/{use-one-call-BwVhWczQ.js → use-one-call-BFIsOrln.js} +1 -1
  21. package/page/index.html +5 -5
  22. package/ui/diff-block.d.ts +6 -11
  23. package/ui/diff-block.js +5 -11
  24. package/ui/studio-conflicts.js +1 -1
  25. package/ui/studio-save.js +13 -12
  26. package/ui/studio.css +4 -26
  27. package/page/assets/index-IqWID6Mh.css +0 -1
@@ -1,4 +1,4 @@
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{i as o,l as s,u as c}from"./SegmentedControlItem-BLuJOusN.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{M as f,U as p,_ as m,k as h,o as g,t as _}from"./browser-transport-CidXgImE.js";import{t as v}from"./mergeProps-ptS-gIMz.js";import{p as y}from"./fieldParts-Cs6Amprh.js";import{t as b}from"./Icon-ZfFwTt8n.js";import{p as x,r as S,t as C,u as ee}from"./IconButton-CG5klqF1.js";import{a as w,d as te,l as T,p as E,u as D}from"./SidePanel-OYp0bLNO.js";import{t as O}from"./Text-BsiAsowd.js";import{a as k,n as A,t as j}from"./labels-provider-BqgbdxdT.js";import{t as M}from"./Dialog-BDUExlk_.js";import{t as N}from"./createReactComponent-CZwsv6DD.js";import{a as P,i as F,t as I}from"./Banner-DgPjY5Yu.js";import{t as L}from"./Center-nHS1JSux.js";import{jr as R}from"./tool-schema-BrqSc6vO.js";import{c as z}from"./host-patterns-C9RMP16Q.js";import{Mn as B,fn as ne,pn as re}from"./shaped-data-BcarWqd5.js";import{g as ie,r as ae,t as oe,x as se}from"./reader-B0gVhfoZ.js";import{i as V}from"./live-ingress-lDUGPwth.js";import{_ as ce,i as le}from"./turn-client-DwVPS3TX.js";import{r as ue,t as de}from"./live-messages-BYi31jQk.js";import{t as fe}from"./EmptyState-C8W4JKBZ.js";import"./PaneState-C8jetBGI.js";import{t as pe}from"./Section-DJ97F7QE.js";import{L as me,N as he,P as ge,X as _e,Y as ve,a as ye,b as be,dt as xe,et as Se,ft as Ce,i as H,kt as we,m as Te,rt as Ee,ut as De,v as Oe,y as ke}from"./index-D7CjWX1v.js";var Ae=N(`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`}]]),je=N(`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`}]]),Me=N(`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`}]]),U=N(`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`}]]),Ne=N(`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`}]]),Pe=N(`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`}]]),W=N(`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`,R(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=De(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`,R(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`,R(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=He(e,t,16e3),r=re(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?.(xe(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?.(Ce(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:le(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=ue(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(se(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?.(se(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=de.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new z(`request`,B(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new z(`request`,B(`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=ne(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`?ce(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{i as o,l as s,u as c}from"./SegmentedControlItem-BLuJOusN.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{M as f,U as p,_ as m,k as h,o as g,t as _}from"./browser-transport-KwpVG2px.js";import{t as v}from"./mergeProps-ptS-gIMz.js";import{p as y}from"./fieldParts-Cs6Amprh.js";import{t as b}from"./Icon-ZfFwTt8n.js";import{p as x,r as S,t as C,u as ee}from"./IconButton-CG5klqF1.js";import{a as w,d as te,l as T,p as E,u as D}from"./SidePanel-OYp0bLNO.js";import{t as O}from"./Text-BsiAsowd.js";import{a as k,n as A,t as j}from"./labels-provider-BqgbdxdT.js";import{t as M}from"./Dialog-BDUExlk_.js";import{t as N}from"./createReactComponent-CZwsv6DD.js";import{a as P,i as F,t as I}from"./Banner-D2s9xjDu.js";import{t as L}from"./Center-nHS1JSux.js";import{jr as R}from"./tool-schema-BrqSc6vO.js";import{c as z}from"./host-patterns-C9RMP16Q.js";import{Mn as B,fn as ne,pn as re}from"./shaped-data-BcarWqd5.js";import{g as ie,r as ae,t as oe,x as se}from"./reader-B0gVhfoZ.js";import{i as V}from"./live-ingress-lDUGPwth.js";import{_ as ce,i as le}from"./turn-client-DwVPS3TX.js";import{r as ue,t as de}from"./live-messages-BYi31jQk.js";import{t as fe}from"./EmptyState-C8W4JKBZ.js";import"./PaneState-C8jetBGI.js";import{t as pe}from"./Section-DJ97F7QE.js";import{L as me,N as he,P as ge,X as _e,Y as ve,a as ye,b as be,dt as xe,et as Se,ft as Ce,i as H,kt as we,m as Te,rt as Ee,ut as De,v as Oe,y as ke}from"./index-C_weLbPu.js";var Ae=N(`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`}]]),je=N(`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`}]]),Me=N(`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`}]]),U=N(`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`}]]),Ne=N(`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`}]]),Pe=N(`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`}]]),W=N(`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`,R(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=De(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`,R(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`,R(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=He(e,t,16e3),r=re(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?.(xe(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?.(Ce(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:le(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=ue(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(se(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?.(se(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=de.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new z(`request`,B(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new z(`request`,B(`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=ne(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`?ce(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&&Ee(r?r.split(`
4
4
  `):[],n?n.split(`
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{g as r}from"./fieldParts-Cs6Amprh.js";import{t as i}from"./Icon-ZfFwTt8n.js";import{r as a,t as o}from"./IconButton-CG5klqF1.js";import{t as s}from"./Text-BsiAsowd.js";import{t as c}from"./createReactComponent-CZwsv6DD.js";import{n as l,t as u}from"./ScrollableArea-C8AVuqnt.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-DeO1319a.js";import{P as v,i as y}from"./workspace-Ck0o-_fd.js";import{t as b}from"./EmptyState-C8W4JKBZ.js";import{t as x}from"./ContextMenu-B-dMscLp.js";import{B as S,Ct as C,Ft as w,J as T,Pt as E,R as D,St as O,V as k,_t as A,bt as j,d as M,n as N,u as P,vt as F,xt as I,yt as L,z as R}from"./index-D7CjWX1v.js";var z=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`}]]),B=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`}]]),V=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`}]]),H=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 U(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 W(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 G(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:W(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,type:u.get(i.provider),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??``):void 0;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:T(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=U([...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:U([...l.values()],n,x)}),S({label:`Shared settings`,nodes:U(p,n,m)},{label:`Models`,nodes:b}),S({label:`Profiles`,nodes:o}),S({label:`Tools`,nodes:U(f,n,m)})].filter(e=>e.length>0),links:n}}function K(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 q(e){let t=K(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=q(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=K(e),r=new Map;for(let{link:i,from:a,to:o}of q(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,J=8,Y=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return q(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)-J,i=Math.max(r.y,...r.joins)+J,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*Y));let x=h(b),{nodes:S,headings:w,boxes:T,ports:E}=x,{right:D,bottom:k}=x,{spans:A,rails:j}=_(E),M=a/2,N=Math.max(o/2,u),P=[],F=new Map,I=Math.max(a,...y.map(e=>e*Y)),L=q(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=T.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:O({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=A.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+(j.get(`${y}:${f}`)??0))*Y,Math.max(v-Y,0)),x=v<32?O(p,m):C(p,m,b,J),S=(e,t)=>t>e.y-N&&t<e.y+e.height+N,w=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(w.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=[...w];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-J+N,width:R-L,height:2*(J-N)}),F.set(V,n),n})();k=Math.max(k,H);let U=d?p.x+l*Y:b,W=d?b:m.x-l*Y,G={x:(U+W)/2,y:H};return[{link:e,from:t,to:n,d:C(p,G,U,J).d+C(G,m,W,J).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(k,l)+l,nodes:S,headings:w,lines:L}}var X=e(n(),1),ce={tokens:{},detail:{},expanded:!1},Z=e=>e===void 0?`${D}.map`:`${D}.map.project:${e}`;function le(e){if(!R(e))return{};let t={};for(let[n,r]of Object.entries(e))R(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(S()?.getItem(Z(e))??`null`);return R(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?S()?.removeItem(Z(e)):S()?.setItem(Z(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}}function me(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let{left:e,top:n}=t(a);if(a.scrollTo({left:e,top:n,behavior:`instant`}),Math.abs(a.scrollLeft-e)<1&&Math.abs(a.scrollTop-n)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var he=e=>e.button===0&&e.pointerType!==`touch`;function ge(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 _e(e){let[t,n]=(0,X.useState)(!1);return{panning:t,pan:t=>{if(!he(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),ge(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Q=t(),ve={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},ye={...ve,node:{width:240,height:84}},be=28;function xe(e){return e.length>be?`${e.slice(0,27)}…`:e}function Se({kind:e,type:t,note:n}){return(e===`agent`?j(t):void 0)||(e===`tool`?I(t??``):e===`model`&&t===`typesafe`?P:e===`model`?M(n)??N.modelBinding:e===`provider`?w:e===`shared`&&t&&Object.hasOwn(N,t)?N[t]:e===`agent`?L.text:E)}function Ce(e){return Object.hasOwn(N,e)?N[e]:E}function $(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 we=4,Te=24,Ee={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function De(e){let t=k()?.name,[n,r]=(0,X.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,X.useMemo)(()=>o===void 0?e:te(e,o),[e,o]),[c,l]=(0,X.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 Oe(e,t,n){let r=(0,X.useRef)(!1),[i,a]=(0,X.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!he(o))return;let c;ge(o,(e,r)=>{!c&&Math.hypot(e,r)<we||(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?Ee[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Te,0),c=Math.max(o.y+a.y*Te,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function ke(e){let[t,n]=(0,X.useState)(),[r,i]=(0,X.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 Ae(e,t,n){let r=(0,X.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,X.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return me(n,e=>{let t=o!==void 0&&(o.x+i.node.width>e.clientWidth||o.y+o.height>e.clientHeight),{left:r,top:a}=pe(n,e);return{left:r+(t?o.x-i.padding:0),top:a+(t?o.y-i.padding-i.heading:0)}})},[e,t,i])}function je(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:V,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?B:z,onClick:s},{label:`Tidy`,icon:H,isDisabled:!a,onClick:c}]}function Me({actions:e,query:t,onQuery:n,onClose:s}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:h,tidy:g}=e;return(0,Q.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Q.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,Q.jsx)(a,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:p,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Q.jsx)(a,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:H,size:`sm`}),onClick:g}),(0,Q.jsx)(o,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:u?B:z,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:h}),(0,Q.jsx)(o,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:r,size:`sm`}),tooltip:`Close the map`,onClick:s})]})}function Ne({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=$(t,i);return(0,Q.jsx)(A,{id:t.id,label:xe(t.long??t.label),icon:Se(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>be?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...Ne(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:r,selected:a,on:o,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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Q.jsx)(i,{icon:Se(t),size:`sm`}),(0,Q.jsx)(s,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Q.jsx)(s,{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,Q.jsx)(`button`,{...h,...u,...Ne(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":$(t,a)?`true`:void 0,children:m}):(0,Q.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":$(t,a)?``:void 0,...Ne(e),...u,children:[(0,Q.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":a===t.id?`true`:void 0,children:m}),f.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":a===e.id?`true`:void 0,"data-on":o.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Q.jsx)(i,{icon:Ce(e.type),size:`sm`}),(0,Q.jsx)(s,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Q.jsx)(s,{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:a}){let{expanded:o,family:c,map:l,moved:d,put:p,showFamily:h,expand:g}=De((0,X.useMemo)(()=>G(e,t),[e,t])),[_,v]=(0,X.useState)(``),y=(0,X.useMemo)(()=>ee(l,_),[l,_]),S=(0,X.useMemo)(()=>_.trim()===``?l:te(l,y),[l,_,y]),C=_.trim()!==``&&y.length===0,w=(0,X.useRef)(null),T=o?ye:ve,E=(0,X.useMemo)(()=>({map:S,expanded:o}),[S,o]),D=F(w,E),O=(0,X.useMemo)(()=>se(S,T,{moved:d,widths:D,detail:o}),[S,T,o,d,D]),k=S.columns.flat().flatMap(e=>e.nodes),A=k.find(e=>$(e,n))?.id;Ae(w,c,{place:A===void 0?void 0:O.nodes[A],sizes:T});let{dragging:j,draggable:M}=Oe(O,d,p),{panning:N,pan:P}=_e(`[data-map-node]`),{lit:I,on:L,onLines:R,lights:z}=ke(O),B={family:c,expanded:o,isMoved:k.some(e=>Object.hasOwn(d,e.id)),showFamily:h,expand:g,tidy:()=>{p({},!0)}},[V,H]=(0,X.useState)(),U=je(k.find(e=>e.id===V),r,B),W=o?Fe:Pe,K=k.find(e=>$(e,n))?.id,q=e=>R.has(e.link)?2:+(e.from===K||e.to===K),ne=[...O.lines].sort((e,t)=>q(e)-q(t));return(0,Q.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,Q.jsx)(u,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Q.jsx)(x,{items:U,label:`Map actions`,"data-map-field":``,children:(0,Q.jsxs)(`div`,{ref:w,className:`studio-map`,"data-lit":I===void 0||j!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:P,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(T.node.width)}px`,"--map-line":`${String(T.card.row)}px`},children:[(0,Q.jsx)(`svg`,{className:`studio-map-lines`,width:O.width,height:O.height,"aria-hidden":`true`,children:ne.map(({link:e,from:t,to:n,d:r})=>(0,Q.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,Q.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Q.jsx)(s,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),k.map(e=>{let t=O.nodes[e.id];return t&&(0,Q.jsx)(W,{node:e,place:t,joins:re(S,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)})]})})}),C&&(0,Q.jsx)(f,{className:`studio-map-nothing`,children:(0,Q.jsx)(b,{headingLevel:2,icon:(0,Q.jsx)(i,{icon:m,size:`lg`}),title:`Nothing matches`})}),(0,Q.jsx)(Me,{actions:B,query:_,onQuery:v,onClose:a})]})}export{Ie as StudioMap};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{g as r}from"./fieldParts-Cs6Amprh.js";import{t as i}from"./Icon-ZfFwTt8n.js";import{r as a,t as o}from"./IconButton-CG5klqF1.js";import{t as s}from"./Text-BsiAsowd.js";import{t as c}from"./createReactComponent-CZwsv6DD.js";import{n as l,t as u}from"./ScrollableArea-C8AVuqnt.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-DeO1319a.js";import{P as v,i as y}from"./workspace-Ck0o-_fd.js";import{t as b}from"./EmptyState-C8W4JKBZ.js";import{t as x}from"./ContextMenu-Bs-xBzLA.js";import{B as S,Ct as C,Ft as w,J as T,Pt as E,R as D,St as O,V as k,_t as A,bt as j,d as M,n as N,u as P,vt as F,xt as I,yt as L,z as R}from"./index-C_weLbPu.js";var z=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`}]]),B=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`}]]),V=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`}]]),H=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 U(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 W(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 G(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:W(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,type:u.get(i.provider),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??``):void 0;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:T(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=U([...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:U([...l.values()],n,x)}),S({label:`Shared settings`,nodes:U(p,n,m)},{label:`Models`,nodes:b}),S({label:`Profiles`,nodes:o}),S({label:`Tools`,nodes:U(f,n,m)})].filter(e=>e.length>0),links:n}}function K(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 q(e){let t=K(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=q(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=K(e),r=new Map;for(let{link:i,from:a,to:o}of q(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,J=8,Y=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return q(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)-J,i=Math.max(r.y,...r.joins)+J,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*Y));let x=h(b),{nodes:S,headings:w,boxes:T,ports:E}=x,{right:D,bottom:k}=x,{spans:A,rails:j}=_(E),M=a/2,N=Math.max(o/2,u),P=[],F=new Map,I=Math.max(a,...y.map(e=>e*Y)),L=q(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=T.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:O({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=A.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+(j.get(`${y}:${f}`)??0))*Y,Math.max(v-Y,0)),x=v<32?O(p,m):C(p,m,b,J),S=(e,t)=>t>e.y-N&&t<e.y+e.height+N,w=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(w.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=[...w];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-J+N,width:R-L,height:2*(J-N)}),F.set(V,n),n})();k=Math.max(k,H);let U=d?p.x+l*Y:b,W=d?b:m.x-l*Y,G={x:(U+W)/2,y:H};return[{link:e,from:t,to:n,d:C(p,G,U,J).d+C(G,m,W,J).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(k,l)+l,nodes:S,headings:w,lines:L}}var X=e(n(),1),ce={tokens:{},detail:{},expanded:!1},Z=e=>e===void 0?`${D}.map`:`${D}.map.project:${e}`;function le(e){if(!R(e))return{};let t={};for(let[n,r]of Object.entries(e))R(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(S()?.getItem(Z(e))??`null`);return R(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?S()?.removeItem(Z(e)):S()?.setItem(Z(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}}function me(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let{left:e,top:n}=t(a);if(a.scrollTo({left:e,top:n,behavior:`instant`}),Math.abs(a.scrollLeft-e)<1&&Math.abs(a.scrollTop-n)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var he=e=>e.button===0&&e.pointerType!==`touch`;function ge(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 _e(e){let[t,n]=(0,X.useState)(!1);return{panning:t,pan:t=>{if(!he(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),ge(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Q=t(),ve={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},ye={...ve,node:{width:240,height:84}},be=28;function xe(e){return e.length>be?`${e.slice(0,27)}…`:e}function Se({kind:e,type:t,note:n}){return(e===`agent`?j(t):void 0)||(e===`tool`?I(t??``):e===`model`&&t===`typesafe`?P:e===`model`?M(n)??N.modelBinding:e===`provider`?w:e===`shared`&&t&&Object.hasOwn(N,t)?N[t]:e===`agent`?L.text:E)}function Ce(e){return Object.hasOwn(N,e)?N[e]:E}function $(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 we=4,Te=24,Ee={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function De(e){let t=k()?.name,[n,r]=(0,X.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,X.useMemo)(()=>o===void 0?e:te(e,o),[e,o]),[c,l]=(0,X.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 Oe(e,t,n){let r=(0,X.useRef)(!1),[i,a]=(0,X.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!he(o))return;let c;ge(o,(e,r)=>{!c&&Math.hypot(e,r)<we||(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?Ee[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Te,0),c=Math.max(o.y+a.y*Te,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function ke(e){let[t,n]=(0,X.useState)(),[r,i]=(0,X.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 Ae(e,t,n){let r=(0,X.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,X.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return me(n,e=>{let t=o!==void 0&&(o.x+i.node.width>e.clientWidth||o.y+o.height>e.clientHeight),{left:r,top:a}=pe(n,e);return{left:r+(t?o.x-i.padding:0),top:a+(t?o.y-i.padding-i.heading:0)}})},[e,t,i])}function je(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:V,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?B:z,onClick:s},{label:`Tidy`,icon:H,isDisabled:!a,onClick:c}]}function Me({actions:e,query:t,onQuery:n,onClose:s}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:h,tidy:g}=e;return(0,Q.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Q.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,Q.jsx)(a,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:p,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Q.jsx)(a,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:H,size:`sm`}),onClick:g}),(0,Q.jsx)(o,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:u?B:z,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:h}),(0,Q.jsx)(o,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Q.jsx)(i,{icon:r,size:`sm`}),tooltip:`Close the map`,onClick:s})]})}function Ne({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=$(t,i);return(0,Q.jsx)(A,{id:t.id,label:xe(t.long??t.label),icon:Se(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>be?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...Ne(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:r,selected:a,on:o,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,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Q.jsx)(i,{icon:Se(t),size:`sm`}),(0,Q.jsx)(s,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Q.jsx)(s,{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,Q.jsx)(`button`,{...h,...u,...Ne(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":$(t,a)?`true`:void 0,children:m}):(0,Q.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":$(t,a)?``:void 0,...Ne(e),...u,children:[(0,Q.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":a===t.id?`true`:void 0,children:m}),f.map(e=>(0,Q.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":a===e.id?`true`:void 0,"data-on":o.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Q.jsx)(i,{icon:Ce(e.type),size:`sm`}),(0,Q.jsx)(s,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Q.jsx)(s,{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:a}){let{expanded:o,family:c,map:l,moved:d,put:p,showFamily:h,expand:g}=De((0,X.useMemo)(()=>G(e,t),[e,t])),[_,v]=(0,X.useState)(``),y=(0,X.useMemo)(()=>ee(l,_),[l,_]),S=(0,X.useMemo)(()=>_.trim()===``?l:te(l,y),[l,_,y]),C=_.trim()!==``&&y.length===0,w=(0,X.useRef)(null),T=o?ye:ve,E=(0,X.useMemo)(()=>({map:S,expanded:o}),[S,o]),D=F(w,E),O=(0,X.useMemo)(()=>se(S,T,{moved:d,widths:D,detail:o}),[S,T,o,d,D]),k=S.columns.flat().flatMap(e=>e.nodes),A=k.find(e=>$(e,n))?.id;Ae(w,c,{place:A===void 0?void 0:O.nodes[A],sizes:T});let{dragging:j,draggable:M}=Oe(O,d,p),{panning:N,pan:P}=_e(`[data-map-node]`),{lit:I,on:L,onLines:R,lights:z}=ke(O),B={family:c,expanded:o,isMoved:k.some(e=>Object.hasOwn(d,e.id)),showFamily:h,expand:g,tidy:()=>{p({},!0)}},[V,H]=(0,X.useState)(),U=je(k.find(e=>e.id===V),r,B),W=o?Fe:Pe,K=k.find(e=>$(e,n))?.id,q=e=>R.has(e.link)?2:+(e.from===K||e.to===K),ne=[...O.lines].sort((e,t)=>q(e)-q(t));return(0,Q.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,Q.jsx)(u,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Q.jsx)(x,{items:U,label:`Map actions`,"data-map-field":``,children:(0,Q.jsxs)(`div`,{ref:w,className:`studio-map`,"data-lit":I===void 0||j!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:P,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(T.node.width)}px`,"--map-line":`${String(T.card.row)}px`},children:[(0,Q.jsx)(`svg`,{className:`studio-map-lines`,width:O.width,height:O.height,"aria-hidden":`true`,children:ne.map(({link:e,from:t,to:n,d:r})=>(0,Q.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,Q.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Q.jsx)(s,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),k.map(e=>{let t=O.nodes[e.id];return t&&(0,Q.jsx)(W,{node:e,place:t,joins:re(S,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)})]})})}),C&&(0,Q.jsx)(f,{className:`studio-map-nothing`,children:(0,Q.jsx)(b,{headingLevel:2,icon:(0,Q.jsx)(i,{icon:m,size:`lg`}),title:`Nothing matches`})}),(0,Q.jsx)(Me,{actions:B,query:_,onQuery:v,onClose:a})]})}export{Ie as StudioMap};
@@ -1 +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{H as a,M as o,c as s,l as c}from"./browser-transport-CidXgImE.js";import{t as l}from"./Icon-ZfFwTt8n.js";import{t as u}from"./IconButton-CG5klqF1.js";import{t as d}from"./Text-BsiAsowd.js";import{n as f,o as p}from"./labels-provider-BqgbdxdT.js";import{n as m}from"./Card-Ghe4ozhC.js";import{t as h}from"./Tooltip-CTEuMRLe.js";import{n as g,t as _}from"./arrive-DvbqpeRS.js";import{d as v}from"./reader-B0gVhfoZ.js";import{_ as y,b,v as x,x as S}from"./studio-console-D59tIXKj.js";import{c as C,i as w}from"./trace-patterns-CS99kExN.js";import{t as T}from"./CardWall-CBRLdDZW.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=m();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 C(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=f(),s=A(),c=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(w,{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:c.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)(d,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(d,{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=f(),s=A(),c=a.length,l=Math.min(c-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(w,{title:e,aside:t,detail:n,value:a[l]===void 0?s.decimal.format(i.score):F(a[l]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(c-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===l),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/c*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(d,{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)(w,{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=f(),i=b(e),a=B(i),[o,l]=(0,E.useState)(null);if(!a)return null;let u=x(t),d=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),p=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(h,{content:p,children:(0,D.jsx)(c,{label:p,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};S(i,t,n).then(l)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(d),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(u.width)}%`,height:`${String(u.height)}%`,left:`${String(u.left)}%`,top:`${String(u.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(s,{isOpen:o!==null,onOpenChange:e=>{e||l(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,field:i,asked:a}){let o=f(),s=a&&y(a.images,a.state,i),c=A(),{top:l,bottom:u,left:d,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(d),top:c.percent.format(l),right:c.percent.format(p),bottom:c.percent.format(u)});return(0,D.jsx)(w,{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(d*100)}%`,insetBlockStart:`${String(l*100)}%`,width:`${String((p-d)*100)}%`,height:`${String((u-l)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let o=f(),s=`${e.id} · ${o(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let c=o(`@theorem.decision.edit_question`,{question:e.id}),d={title:s,detail:i,aside:r?(0,D.jsx)(u,{label:c,tooltip:c,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(l,{icon:a,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,field:e.field,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=f(),c=A();return(0,D.jsx)(g,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(_,{children:(0,D.jsx)(d,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:p(s,c.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=f();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)(T,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(_,{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),a=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>a.current?.abort(),[]);let s=(0,E.useCallback)(()=>{a.current?.abort(),a.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{a.current?.abort();let s=new AbortController;a.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,v(t)),i(e=>({...e,status:`error`,startedAt:null,failure:o(t)}))}finally{a.current===s&&(a.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};
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{H as a,M as o,c as s,l as c}from"./browser-transport-KwpVG2px.js";import{t as l}from"./Icon-ZfFwTt8n.js";import{t as u}from"./IconButton-CG5klqF1.js";import{t as d}from"./Text-BsiAsowd.js";import{n as f,o as p}from"./labels-provider-BqgbdxdT.js";import{n as m}from"./Card-Ghe4ozhC.js";import{t as h}from"./Tooltip-CTEuMRLe.js";import{n as g,t as _}from"./arrive-DvbqpeRS.js";import{d as v}from"./reader-B0gVhfoZ.js";import{_ as y,b,v as x,x as S}from"./studio-console-CawD8qZ8.js";import{c as C,i as w}from"./trace-patterns-CS99kExN.js";import{t as T}from"./CardWall-CBRLdDZW.js";var E=e(n(),1),D=t(),O=`var(--duration-medium) var(--ease-standard)`,k=12;function A(){let e=m();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 C(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=f(),s=A(),c=Object.entries(a.probabilities).sort(([,e],[,t])=>t-e);return(0,D.jsx)(w,{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:c.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)(d,{type:`supporting`,color:`secondary`,maxLines:1,children:e}),(0,D.jsx)(d,{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=f(),s=A(),c=a.length,l=Math.min(c-1,Math.max(0,Math.round(i.score)));return(0,D.jsx)(w,{title:e,aside:t,detail:n,value:a[l]===void 0?s.decimal.format(i.score):F(a[l]),note:[o(`@theorem.decision.score_of`,{score:s.decimal.format(i.score),max:s.decimal.format(c-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===l),transition:`height ${O}`}},`${String(t)}:${e}`)),(0,D.jsx)(`div`,{style:{position:`absolute`,insetBlock:-4,left:`${String((i.score+.5)/c*100)}%`,width:0,borderInlineStart:`1.5px dashed var(--color-text-secondary)`,transition:`left ${O}`}})]}),(0,D.jsx)(`div`,{style:{display:`flex`,gap:4},children:a.map((e,t)=>(0,D.jsx)(`div`,{style:{flex:1,minWidth:0},title:e,children:(0,D.jsx)(d,{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)(w,{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=f(),i=b(e),a=B(i),[o,l]=(0,E.useState)(null);if(!a)return null;let u=x(t),d=a.width*(t.right-t.left)/(a.height*(t.bottom-t.top)),p=r(`@theorem.decision.open_box`);return(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(h,{content:p,children:(0,D.jsx)(c,{label:p,padding:0,onClick:e=>{let n={outline:V(e.currentTarget,`--color-accent`),shade:V(e.currentTarget,`--color-overlay`)};S(i,t,n).then(l)},children:(0,D.jsx)(`div`,{role:`img`,"aria-label":r(`@theorem.decision.box_in`),style:{position:`relative`,overflow:`hidden`,aspectRatio:String(d),height:z,maxWidth:`100%`,borderRadius:4},children:(0,D.jsx)(`img`,{src:i,alt:``,style:{position:`absolute`,width:`${String(u.width)}%`,height:`${String(u.height)}%`,left:`${String(u.left)}%`,top:`${String(u.top)}%`,maxWidth:`none`}})})})}),(0,D.jsx)(s,{isOpen:o!==null,onOpenChange:e=>{e||l(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,field:i,asked:a}){let o=f(),s=a&&y(a.images,a.state,i),c=A(),{top:l,bottom:u,left:d,right:p}=r.box,m=o(`@theorem.decision.box_edges`,{left:c.percent.format(d),top:c.percent.format(l),right:c.percent.format(p),bottom:c.percent.format(u)});return(0,D.jsx)(w,{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(d*100)}%`,insetBlockStart:`${String(l*100)}%`,width:`${String((p-d)*100)}%`,height:`${String((u-l)*100)}%`,borderRadius:2,background:j(!0),transition:`all ${O}`}})})})}function W({question:e,answer:t,asked:n,onQuestion:r,detail:i}){let o=f(),s=`${e.id} · ${o(`@theorem.decision.type.${e.type}`)}`;if(!t)return null;let c=o(`@theorem.decision.edit_question`,{question:e.id}),d={title:s,detail:i,aside:r?(0,D.jsx)(u,{label:c,tooltip:c,size:`sm`,variant:`ghost`,icon:(0,D.jsx)(l,{icon:a,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,field:e.field,asked:n})}function G({model:e,usage:t,elapsedMs:n,isStale:i,tokens:a,children:o}){let s=f(),c=A();return(0,D.jsx)(g,{children:(0,D.jsxs)(r,{gap:3,style:{opacity:i?.5:1,transition:`opacity ${O}`},"aria-busy":i,children:[o,(0,D.jsx)(_,{children:(0,D.jsx)(d,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:p(s,c.usd,{model:e,usage:t,elapsedMs:n,tokens:a})})})]},n??0)})}function K({iface:e,result:t,elapsedMs:n,isStale:r,asked:i,onQuestion:a,questionText:o}){let s=f();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)(T,{minWidth:260,children:e.questions.map(e=>(0,D.jsx)(_,{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),a=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>a.current?.abort(),[]);let s=(0,E.useCallback)(()=>{a.current?.abort(),a.current=null,i(e=>e.status===t?{...e,status:e.result?`done`:`idle`,startedAt:null}:e)},[t]),c=(0,E.useCallback)(async(...r)=>{a.current?.abort();let s=new AbortController;a.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,v(t)),i(e=>({...e,status:`error`,startedAt:null,failure:o(t)}))}finally{a.current===s&&(a.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-D7CjWX1v.js"></script>
13
+ <script type="module" crossorigin src="/studio/assets/index-C_weLbPu.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">
@@ -43,7 +43,7 @@
43
43
  <link rel="modulepreload" crossorigin href="/studio/assets/SidePanel-OYp0bLNO.js">
44
44
  <link rel="modulepreload" crossorigin href="/studio/assets/IconAlertTriangle-BqAEqqdU.js">
45
45
  <link rel="modulepreload" crossorigin href="/studio/assets/labels-provider-BqgbdxdT.js">
46
- <link rel="modulepreload" crossorigin href="/studio/assets/Banner-DgPjY5Yu.js">
46
+ <link rel="modulepreload" crossorigin href="/studio/assets/Banner-D2s9xjDu.js">
47
47
  <link rel="modulepreload" crossorigin href="/studio/assets/arrive-DvbqpeRS.js">
48
48
  <link rel="modulepreload" crossorigin href="/studio/assets/Center-nHS1JSux.js">
49
49
  <link rel="modulepreload" crossorigin href="/studio/assets/IconSearch-BTx66a40.js">
@@ -59,7 +59,7 @@
59
59
  <link rel="modulepreload" crossorigin href="/studio/assets/types-EVrOoUBG.js">
60
60
  <link rel="modulepreload" crossorigin href="/studio/assets/useScrollLock-Dyf6PHJt.js">
61
61
  <link rel="modulepreload" crossorigin href="/studio/assets/useContainerReveal-BFy8N_QU.js">
62
- <link rel="modulepreload" crossorigin href="/studio/assets/browser-transport-CidXgImE.js">
62
+ <link rel="modulepreload" crossorigin href="/studio/assets/browser-transport-KwpVG2px.js">
63
63
  <link rel="modulepreload" crossorigin href="/studio/assets/focusReturn-CTppP2k0.js">
64
64
  <link rel="modulepreload" crossorigin href="/studio/assets/chainEventHandlers-C6ttXGfW.js">
65
65
  <link rel="modulepreload" crossorigin href="/studio/assets/Dialog-BDUExlk_.js">
@@ -76,10 +76,10 @@
76
76
  <link rel="modulepreload" crossorigin href="/studio/assets/useAdaptivePresentation-BY_zvjIp.js">
77
77
  <link rel="modulepreload" crossorigin href="/studio/assets/Section-DJ97F7QE.js">
78
78
  <link rel="modulepreload" crossorigin href="/studio/assets/CollapsibleGroup-toq0Nedn.js">
79
- <link rel="modulepreload" crossorigin href="/studio/assets/ContextMenu-B-dMscLp.js">
79
+ <link rel="modulepreload" crossorigin href="/studio/assets/ContextMenu-Bs-xBzLA.js">
80
80
  <link rel="modulepreload" crossorigin href="/studio/assets/BottomSheet-BQPskY35.js">
81
81
  <link rel="stylesheet" crossorigin href="/studio/assets/PaneState-CnxaP3LD.css">
82
- <link rel="stylesheet" crossorigin href="/studio/assets/index-IqWID6Mh.css">
82
+ <link rel="stylesheet" crossorigin href="/studio/assets/index-Oo9otEIT.css">
83
83
  <style>html{color-scheme:dark}html,body{margin:0;background:#000}html[data-boot-pending],html[data-boot-pending] body{background:#262626}html[data-boot-pending] .astryx-app-shell{height:100dvh}html[data-boot-pending] .astryx-app-shell-sidenav{position:absolute;inset-block:0;inset-inline-start:0;z-index:0;width:3rem}html[data-boot-pending] #astryx-app-shell-main{position:relative;z-index:1;width:100%;height:100%;max-width:none;margin:0;border-radius:0;clip-path:none;background:#262626;color:#fff}html[data-boot-pending] #astryx-app-shell-main>:not([data-boot]){visibility:hidden}html[data-boot-pending] [data-boot]{position:absolute;inset:0;z-index:2;display:grid;place-items:center;background:#262626;color:#fff}</style>
84
84
  <noscript> <style>html[data-boot-pending],html[data-boot-pending] body{background:#000}html[data-boot-pending] #astryx-app-shell-main>:not([data-boot]){visibility:visible !important}[data-boot]{display:none !important}</style>
85
85
  </noscript>
@@ -1,21 +1,16 @@
1
1
  import type { DiffLine } from '../mod.ts';
2
2
  /**
3
- * Changed lines as a unified diff: removed lines red, added lines green, the lines both share
4
- * between. `sides` names what the `-` and the `+` lines each are. `start` numbers the lines as
5
- * the file had them. `kept` is the side that stands, and the other reads as set aside.
3
+ * Two values as a unified diff, read as prose: removed lines red, added lines green, the lines
4
+ * both share between. `sides` names what the `-` and the `+` lines each are, and `kept` is the
5
+ * side that stands, so the other reads as set aside.
6
6
  */
7
- export declare function DiffBlock({ title, lines, sides, start, kept, isWrapped, maxHeight, }: {
8
- title?: string;
7
+ export declare function DiffBlock({ lines, sides, kept, maxHeight, }: {
9
8
  lines: readonly DiffLine[];
10
9
  /** What the `-` lines and the `+` lines each are. */
11
- sides?: {
10
+ sides: {
12
11
  removed: string;
13
12
  added: string;
14
13
  };
15
- /** The one-based line of the file the first line is. Without it the lines are not numbered. */
16
- start?: number;
17
- kept?: '-' | '+';
18
- /** Whether a long line wraps, for text read as prose. Code scrolls sideways. */
19
- isWrapped?: boolean;
14
+ kept: '-' | '+';
20
15
  maxHeight?: string;
21
16
  }): import("react").JSX.Element;
package/ui/diff-block.js CHANGED
@@ -1,17 +1,11 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  const SIGN_LABEL = { ' ': undefined, '-': 'Removed', '+': 'Added' };
3
3
  /**
4
- * Changed lines as a unified diff: removed lines red, added lines green, the lines both share
5
- * between. `sides` names what the `-` and the `+` lines each are. `start` numbers the lines as
6
- * the file had them. `kept` is the side that stands, and the other reads as set aside.
4
+ * Two values as a unified diff, read as prose: removed lines red, added lines green, the lines
5
+ * both share between. `sides` names what the `-` and the `+` lines each are, and `kept` is the
6
+ * side that stands, so the other reads as set aside.
7
7
  */
8
- export function DiffBlock({ title, lines, sides, start, kept, isWrapped = false, maxHeight, }) {
8
+ export function DiffBlock({ lines, sides, kept, maxHeight, }) {
9
9
  const count = (sign) => lines.filter((line) => line.sign === sign).length;
10
- // A line the change adds is not one the file had, so it takes no number.
11
- let at = (start ?? 1) - 1;
12
- return (_jsxs("figure", { className: "studio-diff", "data-wrapped": isWrapped, "data-kept": kept, children: [_jsxs("figcaption", { className: "studio-diff-head", children: [sides ? (_jsxs("span", { className: "studio-diff-sides", children: [_jsx("span", { "data-sign": "-", children: `− ${sides.removed}` }), _jsx("span", { "data-sign": "+", children: `+ ${sides.added}` })] })) : (_jsx("span", { className: "studio-diff-title", children: title })), _jsxs("span", { className: "studio-diff-count", children: [_jsx("span", { "data-sign": "+", children: `+${String(count('+'))}` }), _jsx("span", { "data-sign": "-", children: `−${String(count('-'))}` })] })] }), _jsx("div", { className: "studio-diff-lines", style: { maxHeight }, children: lines.map((line, index) => {
13
- if (line.sign !== '+')
14
- at += 1;
15
- return (_jsxs("div", { className: "studio-diff-line", "data-sign": line.sign, children: [start !== undefined && (_jsx("span", { className: "studio-diff-number", "aria-hidden": true, children: line.sign === '+' ? '' : String(at) })), _jsx("span", { className: "studio-diff-sign", role: "img", "aria-label": SIGN_LABEL[line.sign], children: line.sign === '-' ? '−' : line.sign }), _jsx("code", { children: line.text || ' ' })] }, index));
16
- }) })] }));
10
+ return (_jsxs("figure", { className: "studio-diff", "data-kept": kept, children: [_jsxs("figcaption", { className: "studio-diff-head", children: [_jsxs("span", { className: "studio-diff-sides", children: [_jsx("span", { "data-sign": "-", children: `− ${sides.removed}` }), _jsx("span", { "data-sign": "+", children: `+ ${sides.added}` })] }), _jsxs("span", { className: "studio-diff-count", children: [_jsx("span", { "data-sign": "+", children: `+${String(count('+'))}` }), _jsx("span", { "data-sign": "-", children: `−${String(count('-'))}` })] })] }), _jsx("div", { className: "studio-diff-lines", style: { maxHeight }, children: lines.map((line, index) => (_jsxs("div", { className: "studio-diff-line", "data-sign": line.sign, children: [_jsx("span", { className: "studio-diff-sign", role: "img", "aria-label": SIGN_LABEL[line.sign], children: line.sign === '-' ? '−' : line.sign }), _jsx("code", { children: line.text || ' ' })] }, index))) })] }));
17
11
  }
@@ -76,7 +76,7 @@ export function FileConflicts({ conflicts, files, onApply, onClose, }) {
76
76
  }, children: [_jsx(ToggleButton, { value: "source", label: "Keep source code" }), _jsx(ToggleButton, { value: "studio", label: "Keep studio edit" })] })] }), _jsx(DiffBlock, { lines: lineDiff(valueText(conflict, 'source'), valueText(conflict, 'studio')), sides: {
77
77
  removed: sourceName,
78
78
  added: SIDE_NAME.studio,
79
- }, kept: pick === 'studio' ? '+' : '-', isWrapped: true, maxHeight: DIFF_MAX_HEIGHT })] }, id));
79
+ }, kept: pick === 'studio' ? '+' : '-', maxHeight: DIFF_MAX_HEIGHT })] }, id));
80
80
  }) }) }) }), footer: _jsx(LayoutFooter, { children: _jsxs(HStack, { gap: 2, justify: "between", children: [_jsx(HStack, { gap: 2, children: !one && (_jsxs(_Fragment, { children: [_jsx(Button, { label: "Keep all source code", variant: "ghost", onClick: () => {
81
81
  all('source');
82
82
  } }), _jsx(Button, { label: "Keep all studio edits", variant: "ghost", onClick: () => {
package/ui/studio-save.js CHANGED
@@ -17,8 +17,7 @@ import { Token } from '@astryxdesign/core/Token';
17
17
  import { VStack } from '@astryxdesign/core/VStack';
18
18
  import { IconFiles, IconListDetails } from '@tabler/icons-react';
19
19
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react';
20
- import { atStart, removeAgent, resetAgent, startedHere, } from "../mod.js";
21
- import { DiffBlock } from "./diff-block.js";
20
+ import { atStart, removeAgent, resetAgent, startedHere } from "../mod.js";
22
21
  import { reviewSave, undoSave, writeSave } from "./lib/studio-project.js";
23
22
  import { RefusalDetail } from "./refusal-detail.js";
24
23
  /** Wide enough for a reason's sentence to read in a few lines. */
@@ -96,17 +95,19 @@ function reason(change) {
96
95
  return 'The studio could not find where your files set this.';
97
96
  }
98
97
  }
99
- /** One run of changed lines: the lines taken out marked `-`, the lines put in marked `+`. */
98
+ /** One run of changed lines as a unified diff over the file's own language. */
100
99
  function HunkBlock({ file, hunk }) {
101
- const signed = (sign) => (text) => ({ sign, text });
102
- return (_jsx(DiffBlock, { title: file.created || file.removed
103
- ? `${fileNote(file)} · ${file.file}`
104
- : `${file.file}:${String(hunk.line)}`, start: hunk.line - hunk.lead.length, lines: [
105
- ...hunk.lead.map(signed(' ')),
106
- ...hunk.removed.map(signed('-')),
107
- ...hunk.added.map(signed('+')),
108
- ...hunk.trail.map(signed(' ')),
109
- ] }));
100
+ const signed = (sign) => (text) => `${sign}${text}`;
101
+ const code = [
102
+ ...hunk.lead.map(signed(' ')),
103
+ ...hunk.removed.map(signed('-')),
104
+ ...hunk.added.map(signed('+')),
105
+ ...hunk.trail.map(signed(' ')),
106
+ ].join('\n');
107
+ const place = file.created || file.removed
108
+ ? `${fileNote(file)} · ${file.file}`
109
+ : `${file.file}:${String(hunk.line)}`;
110
+ return (_jsx(CodeBlock, { code: code, language: file.file.split('.').at(-1), title: `${place} · +${String(hunk.added.length)} −${String(hunk.removed.length)}`, isDiff: true, size: "sm" }));
110
111
  }
111
112
  /** What happens to a file: it is new, it goes, or how many places in it change. */
112
113
  function fileNote(file) {
package/ui/studio.css CHANGED
@@ -315,13 +315,6 @@ button.inspector-origin:hover {
315
315
  color: var(--color-text-secondary);
316
316
  }
317
317
 
318
- .studio-diff-title {
319
- min-width: 0;
320
- overflow: hidden;
321
- text-overflow: ellipsis;
322
- white-space: nowrap;
323
- }
324
-
325
318
  .studio-diff-sides {
326
319
  display: flex;
327
320
  flex-wrap: wrap;
@@ -344,18 +337,14 @@ button.inspector-origin:hover {
344
337
  color: var(--color-text-green);
345
338
  }
346
339
 
347
- /* The gutters size to their widest cell and every line shares them. */
340
+ /* The sign gutter sizes to its widest cell and every line shares it. */
348
341
  .studio-diff-lines {
349
342
  display: grid;
350
- grid-template-columns: repeat(2, max-content) minmax(max-content, 1fr);
343
+ grid-template-columns: max-content minmax(0, 1fr);
351
344
  overflow: auto;
352
345
  padding-block: var(--spacing-1);
353
346
  }
354
347
 
355
- .studio-diff[data-wrapped="true"] .studio-diff-lines {
356
- grid-template-columns: repeat(2, max-content) minmax(0, 1fr);
357
- }
358
-
359
348
  .studio-diff-line {
360
349
  display: grid;
361
350
  grid-column: 1 / -1;
@@ -370,17 +359,11 @@ button.inspector-origin:hover {
370
359
  background: var(--color-background-green);
371
360
  }
372
361
 
373
- .studio-diff-number,
374
362
  .studio-diff-sign {
375
363
  padding-inline: var(--spacing-2);
376
364
  color: var(--color-text-secondary);
377
- text-align: end;
378
- user-select: none;
379
- }
380
-
381
- .studio-diff-sign {
382
- grid-column: 2;
383
365
  text-align: center;
366
+ user-select: none;
384
367
  }
385
368
 
386
369
  .studio-diff-line[data-sign="-"] .studio-diff-sign {
@@ -392,16 +375,11 @@ button.inspector-origin:hover {
392
375
  }
393
376
 
394
377
  .studio-diff-line code {
395
- grid-column: 3;
396
378
  padding-inline-end: var(--spacing-3);
397
379
  font: inherit;
398
- white-space: pre;
399
- transition: opacity 120ms ease;
400
- }
401
-
402
- .studio-diff[data-wrapped="true"] .studio-diff-line code {
403
380
  white-space: pre-wrap;
404
381
  overflow-wrap: anywhere;
382
+ transition: opacity 120ms ease;
405
383
  }
406
384
 
407
385
  /* The side that does not stand is set aside: struck through and faint. */