@theoremjs/studio 0.3.4-next.847.g6513d7e → 0.3.4-next.851.g9ebce61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -4
- package/page/assets/{BottomSheet-vAeXbo6j.js → BottomSheet-BAmU8YgD.js} +1 -1
- package/page/assets/{ConsoleFrame-1n_sABmX.js → ConsoleFrame-Dz65yVLC.js} +1 -1
- package/page/assets/{DateInput-DpZtfChG.js → DateInput-DUwL1wep.js} +1 -1
- package/page/assets/{MenuBottomSheet-B7CP4Lsr.js → MenuBottomSheet-DfZYjgL0.js} +1 -1
- package/page/assets/{SchemaFields-CXD7c72E.js → SchemaFields-D7UGra6l.js} +1 -1
- package/page/assets/{TokenizerBottomSheet-Cu3kzKeo.js → TokenizerBottomSheet-C38WRzIr.js} +1 -1
- package/page/assets/{ToolResultCharts-DVYs8fEi.js → ToolResultCharts-Cx0g4QOl.js} +1 -1
- package/page/assets/{Toolbar-CE6Lf31u.js → Toolbar-DAp_Uw5z.js} +1 -1
- package/page/assets/{TraceInspector-BiZXdbiO.js → TraceInspector-EPGzIZ77.js} +1 -1
- package/page/assets/{TraceOverview-BGJeBaBA.js → TraceOverview-B2Q3oXth.js} +1 -1
- package/page/assets/{browser-engine-BPM5Nk_h.js → browser-engine-BLzr3h8d.js} +1 -1
- package/page/assets/{browser-transport-CbYs8r-W.js → browser-transport-eZfjcJk5.js} +2 -2
- package/page/assets/{export-agent-DMuAKRCy.js → export-agent-CWRtT-CD.js} +1 -1
- package/page/assets/{guardrail-tester-BrUjQBZe.js → guardrail-tester-ChwY3tNK.js} +1 -1
- package/page/assets/{index-D2y4CjDY.js → index-CiwarrRR.js} +10 -10
- package/page/assets/{json-code-3X-j_JYu.js → json-code-B-K2AgWe.js} +1 -1
- package/page/assets/{labels-provider-DfcbklTS.js → labels-provider-9Mz_CB_a.js} +2 -2
- package/page/assets/{prompt-row-Bf15WWbA.js → prompt-row-b0TB5Vmr.js} +1 -1
- package/page/assets/{studio-code-pane-DTq-NEj9.js → studio-code-pane-mGW79UA_.js} +1 -1
- package/page/assets/{studio-console-BFsT1OdM.js → studio-console-CCRqaMr7.js} +1 -1
- package/page/assets/{studio-decision-CLgqn34e.js → studio-decision-uoibaDre.js} +1 -1
- package/page/assets/{studio-embedding-6qdjR5xf.js → studio-embedding-DROnuZS6.js} +1 -1
- package/page/assets/{studio-host-console-DJ5Xg7dh.js → studio-host-console-C8aseoTf.js} +2 -2
- package/page/assets/{studio-labels-B-e0Wofl.js → studio-labels-BZWk1UYO.js} +2 -2
- package/page/assets/{studio-live-COBsd-IC.js → studio-live-yHnMF1Qq.js} +2 -2
- package/page/assets/{studio-map-BPAftdD5.js → studio-map-CrNgkX45.js} +1 -1
- package/page/assets/{studio-trace-replay-Y4NSmcA3.js → studio-trace-replay-B07jE5Hs.js} +1 -1
- package/page/assets/{use-one-call-CvLcEx5b.js → use-one-call-59M2irwm.js} +1 -1
- package/page/index.html +4 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ToolResultCharts-
|
|
2
|
-
import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{d as n,l as r,r as i,u as a}from"./themeProps-Bo2jNkIC.js";import{t as o}from"./mergeProps-ptS-gIMz.js";import{t as s}from"./Token-BZrQH6-I.js";import{t as c}from"./isRenderable-DHkzpAoQ.js";import{t as l}from"./Text-BDwNaqzZ.js";import{t as u}from"./preload-helper-DpV6A1kQ.js";import{b as d,i as f,s as p,u as m,v as h}from"./browser-transport-CbYs8r-W.js";import{t as ee}from"./Tooltip-Dhy5lIDA.js";import{t as te}from"./row-keys-0Bn7ZyYy.js";import{_ as ne,f as re,g as ie,m as ae,n as oe,r as g,t as _,v as se}from"./studio-labels-B-e0Wofl.js";import{t as ce}from"./IconMathFunction-CyMTpj2z.js";import{t as le}from"./IconWorld-DkkGLUyH.js";import{l as ue,u as de}from"./tool-schema-Cqelak6O.js";import{_ as fe,a as v,b as y,c as b,f as pe,h as x,l as S,n as C,o as me,r as he,t as ge,v as _e,x as ve,y as w}from"./shaped-data-CjB-teds.js";import{C as ye,d as be,i as xe}from"./turn-client-_TUC5_DY.js";import{t as Se}from"./EmptyState-DVoDGbtj.js";import{t as Ce}from"./use-second-ticker-ovc65-Bo.js";import{i as we,l as T,n as E,t as D}from"./labels-provider-DfcbklTS.js";import{t as O}from"./useLocale-d7ARRGFj.js";import{t as k}from"./HStack-CqE4exX9.js";import{t as A}from"./VStack-CCYGIv4A.js";import{n as Te,t as Ee}from"./ListItem-BevY6nJP.js";import{a as De,i as Oe,o as ke,r as Ae,t as je}from"./ConsoleFrame-1n_sABmX.js";import{i as Me}from"./trace-patterns-DFMwRU00.js";import{n as Ne,t as Pe}from"./studio-console-BFsT1OdM.js";import{t as Fe}from"./SchemaFields-CXD7c72E.js";import{B as Ie,D as Le,N as Re,O as ze,Q as Be,R as Ve,T as He,ft as Ue,ht as We,k as j,lt as Ge,pt as Ke,st as qe,ut as Je,z as M}from"./index-D2y4CjDY.js";var Ye=4,Xe=3,Ze=3,N=8,Qe=6,P=3,$e=3,et=/(^|_)(id|ids|lat|lon|lng|latitude|longitude|offset|interval|index|rank|order)$|Id$|^(generationtime_ms|utc_offset_seconds)$/i,tt=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function nt(e){if(/\s/.test(e))return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&tt.test(t.pathname)}catch{return!1}}function F(e){return!et.test(e)}function I(e){return/^[A-Z][A-Z0-9]{1,5}$/.test(e)?e:v(e)}function L(e,t){if(!F(e)||t&&e in t&&pe(t[e])===void 0)return;let{label:n,unit:r}=he(e,t);return{label:I(e)===e?e:n,unit:r}}function R(e,t){let n=[];for(let[r,i]of x(e)){if(typeof i!=`number`||!Number.isFinite(i))continue;let e=L(r,t);e&&n.push({key:r,value:i,...e})}return n.sort((e,t)=>Number(t.unit!==void 0)-Number(e.unit!==void 0)).slice(0,Ye)}function rt(e){if(!b(e))return[];for(let[t,n]of x(e)){let r=y(n);if(!b(r)||C(r))continue;let i=Object.values(r);if(i.length===0||!i.every(me))continue;let a=R(r,w(e,t));if(a.length>0)return a}return R(e,void 0)}function z(e,t){return new Set(e.map(e=>e[t])).size}function B(e,t,n){return[...new Set(e.flatMap(e=>Object.keys(e)))].filter(n=>n!==t&&e.every(e=>typeof e[n]==`number`||e[n]===null)&&z(e,n)>1).flatMap(e=>{let t=L(e,n);return t?[{key:e,...t}]:[]})}function it(e){let[t]=e;if(t)return Object.keys(t).find(t=>e.every(e=>typeof e[t]==`string`&&ge.test(e[t])))}function at(e){let t=e.map(e=>e.label.split(` `)),[n=[]]=t,r=0;for(;r<n.length&&t.every(e=>e.length>r+1&&e[r]===n[r]);)r++;if(r)return{title:n.slice(0,r).join(` `),series:e.map((e,n)=>{let i=(t[n]??[]).slice(r).join(` `);return{...e,label:i.charAt(0).toUpperCase()+i.slice(1)}})}}function ot(e,t,n,r,i){let a=new Map;for(let e of B(n,r,i)){let t=a.get(e.unit??``)??[];t.push(e),a.set(e.unit??``,t)}return[...a.values()].map(i=>{let a=i.slice(0,Ze),o=a.length>1?at(a):void 0;return{kind:`time`,key:`${e}:${a.map(e=>e.key).join(`+`)}`,title:a.length===1?a[0]?.label??t:o?.title??(t||a.map(e=>e.label).join(` · `)),x:r,series:o?.series??a,rows:n}})}function st(e){let[t]=e,n=t?_e(t):void 0;if(!t||!n||!e.every(e=>typeof e[n]==`string`||typeof e[n]==`number`))return;if(z(e,n)===e.length)return n;let r=t=>e.reduce((e,n)=>e+String(n[t]).length,0),[i]=Object.keys(t).filter(t=>e.every(e=>typeof e[t]==`string`)&&z(e,t)===e.length).sort((e,t)=>r(e)-r(t));return i??n}function ct(e,t,n,r){let i=st(n);return i?B(n,i,r).sort((e,t)=>z(n,t.key)-z(n,e.key)).map(r=>({kind:`category`,key:`${e}:${r.key}`,title:t?`${t} · ${r.label}`:r.label,series:r,rows:n.filter(e=>typeof e[r.key]==`number`).map(e=>({label:String(e[i]),value:e[r.key]})).sort((e,t)=>t.value-e.value).slice(0,N)})):[]}function V(e,t,n,r){if(n.length<P)return[];let i=it(n);return i?ot(e,t,n,i,r):ct(e,t,n,r)}function H(e,t,n,r,i){if(i>$e)return[];if(Array.isArray(e)){let i=e.map(y);return i.every(b)?V(t,n,i,r):[]}if(!b(e))return[];let a=C(e);if(a)return V(t,n,fe(e,a),r);let o=x(e),s=o.filter(([e,t])=>typeof t==`number`&&F(e));if(i>0&&s.length>=P&&s.length===o.length){let e=s.map(([e,t])=>({label:I(e),value:t}));return[{kind:`category`,key:t,title:n,series:{key:`value`,label:n},rows:e.sort((e,t)=>t.value-e.value).slice(0,N)}]}return o.flatMap(([r,a])=>H(y(a),t?`${t}.${r}`:r,i===0?v(r):`${n} › ${v(r)}`,w(e,r),i+1))}function U(e,t,n,r){if(r.size>=Qe||n>4)return;let i=y(e);if(typeof i==`string`)nt(i)&&!r.has(i)&&r.set(i,{src:i,alt:v(t||`image`)});else if(Array.isArray(i))for(let e of i)U(e,t,n+1,r);else if(b(i))for(let[e,t]of Object.entries(i))U(t,e,n+1,r)}function lt(e){let t=y(e),n=new Map;return U(t,``,0,n),{figures:rt(t),charts:H(t,``,``,void 0,0).slice(0,Xe),images:[...n.values()]}}function ut(e){return e.mimeType&&e.data?`data:${e.mimeType};base64,${e.data}`:void 0}function dt(e,t,n){let r=t.flatMap(e=>{let t=ut(e);return t?[{type:e.type,src:t,mimeType:e.mimeType}]:[]});return{images:[...r.filter(e=>e.type===`image`).map(({src:e})=>({src:e,alt:n})),...e.images],audio:r.filter(e=>e.type===`audio`).map(({src:e,mimeType:t})=>({src:e,...t?{mimeType:t}:{}}))}}function ft(e,t){return e.figures.length+e.charts.length+t.images.length+t.audio.length>0}var pt=864e5,mt=10;function ht(e){return e.some(e=>e.includes(`T`))?{tick:Math.abs(Date.parse(e.at(-1)??``)-Date.parse(e[0]??``))<=pt?{hour:`numeric`}:{month:`short`,day:`numeric`},when:{dateStyle:`medium`,timeStyle:`short`}}:{tick:e.length<=mt?{weekday:`short`,timeZone:`UTC`}:{month:`short`,day:`numeric`,timeZone:`UTC`},when:{dateStyle:`medium`,timeZone:`UTC`}}}var W=r(),G={base:{k1xSpc:`x3nfvp2`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,kaIpWk:`x16rqkct`,kmuXW:`x2lah0s`,kzqmXN:`x1xc55vz`,kZKoxP:`xdk7pt`,$$css:!0},pulsing:{kKVMdj:`x1mta51n`,k44tkh:`x1c74tu6`,kyAemX:`x4hg4is`,ko0y90:`xa4qsjk`,$$css:!0},reducedMotion:{kjO2d4:`x1aquc0h`,$$css:!0}},gt={success:{kWkggS:`xdsz4j9`,kMwMTN:`xri61p4`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},warning:{kWkggS:`x1q8g9m5`,kMwMTN:`xrebv38`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},error:{kWkggS:`x1pjz0fi`,kMwMTN:`x1m024r3`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},accent:{kWkggS:`x1ewilqj`,kMwMTN:`x17wrial`,$$css:!0},neutral:{kWkggS:`x1q5y3ey`,kMwMTN:`xrkvqaz`,$$css:!0}};function K({variant:e,label:t,isPulsing:n=!1,tooltip:r,icon:s,xstyle:l,className:u,style:d,ref:f,...p}){let m=c(s),h=(0,W.jsx)(`span`,{ref:f,role:`img`,"aria-label":t,...o(i(`status-dot`,{variant:e}),a(G.base,gt[e],n&&G.pulsing,n&&G.reducedMotion,l),u,d),...p,children:m&&(0,W.jsx)(`span`,{"aria-hidden":`true`,className:`x78zum5 x6s0dn4 xl56j7k x14ju556 x1xc55vz xdk7pt`,children:s})});return r?(0,W.jsx)(ee,{content:r,children:h}):h}K.displayName=`StatusDot`;var _t=new Set([`gate`,`background`,`complete`,`error`,`cancel`]);function vt({call:e,failure:t,isRunning:n}){let r=e?.state?.phase;return r!==void 0&&_t.has(r)?r:t?`error`:n?`running`:`cancel`}function q({call:e,failure:t}){if(t)return{title:t.error};let n=e?.state;if(n?.phase!==`error`)return null;let{error:r,message:i}=n.failure;return r?r===i?{title:r}:{title:r,description:i}:{title:i}}function yt(e){let t=e.tools.find(t=>t.name===e.picked)??e.tools[0],n=t?e.drafts[t.name]??S(de(t.inputSchema)):``,r=e.calls.filter(e=>e.name===t?.name),i=r.find(t=>t.id===e.shownId)??r[0]??null;return{tool:t,text:n,shown:i,earlier:e.calls.filter(e=>e!==i)}}var J=t(n(),1);function bt(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`call-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function xt(e,t){let n=[...e.events,t],r=t.type===`tool`&&t.tool.phase===`progress`?t.tool.data:e.progress;return{...e,events:n,call:ye(n)[0]??null,progress:r}}function St(e,t){let n=(0,J.useMemo)(()=>se(e,t),[e,t]),{iface:r,describeFailure:i}=He(n),[a,o]=(0,J.useState)([]),s=(0,J.useRef)(new Map),c=(0,J.useRef)([]),l=(0,J.useRef)(a);l.current=a,(0,J.useEffect)(()=>{let e=s.current;return()=>{for(let t of e.values())t.abort()}},[]);let u=(0,J.useCallback)((e,t)=>{o(n=>n.map(n=>n.id===e?t(n):n))},[]),f=(0,J.useCallback)(async(e,t)=>{let n=new AbortController;s.current.set(e,n);let r=performance.now();u(e,e=>({...e,isRunning:!0,failure:null}));try{await t(t=>{t.type!==`unsupported`&&t.type!==`malformed`&&u(e,e=>xt(e,t))},n.signal),u(e,e=>({...e,isRunning:!1,answering:null,elapsedMs:performance.now()-r}))}catch(t){let i=n.signal.aborted?null:d(t);u(e,e=>({...e,isRunning:!1,answering:null,failure:i,elapsedMs:performance.now()-r}))}finally{s.current.get(e)===n&&s.current.delete(e)}},[u]);return{iface:r,describeFailure:i,calls:a,run:(0,J.useCallback)((e,t)=>{let r=bt();return o(n=>[{id:r,name:e,input:t,events:[],call:null,progress:void 0,isRunning:!0,failure:null,answering:null,startedAt:Date.now(),elapsedMs:null},...n]),f(r,(r,i)=>n.call({name:e,input:t},r,i)),r},[f,n]),answer:(0,J.useCallback)(async(e,t)=>{let r=l.current.find(t=>t.id===e),i=r?.call?.state;if(!r?.call||i?.phase!==`gate`)return;let a=r.call.callId,o=xe(r.call),s=ne({toolName:r.name,gate:i.gate,sessionPermissions:c.current,resolution:t});s.decision===`approve`&&(c.current=s.sessionPermissions);let d=be(r.events);u(e,e=>({...e,answering:t.action})),await f(e,(e,t)=>n.invoke({gateId:a,operationId:o,decision:s.decision,...s.decision===`approve`&&s.secret!==void 0?{secret:s.secret}:{},replay:{name:r.name,input:i.gate.preparedArguments??r.input,gateKind:i.gate.kind,sessionPermissions:c.current,...d?{snapshot:d}:{}}},e,t))},[f,n,u]),cancel:(0,J.useCallback)(e=>{s.current.get(e)?.abort(),s.current.delete(e)},[])}}function Ct(e){return(0,W.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":!0,...e,children:(0,W.jsx)(`path`,{d:`M13.85 0a4.16 4.16 0 0 0-2.95 1.217L1.456 10.66a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l9.442-9.442a2.49 2.49 0 0 1 3.541 0 2.49 2.49 0 0 1 0 3.541L8.59 12.97l-.1.1a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l.1-.098 7.03-7.034a2.49 2.49 0 0 1 3.542 0l.049.05a2.49 2.49 0 0 1 0 3.54l-8.54 8.54a1.96 1.96 0 0 0 0 2.755l1.753 1.753a.835.835 0 0 0 1.18 0 .835.835 0 0 0 0-1.18l-1.753-1.753a.266.266 0 0 1 0-.394l8.54-8.54a4.185 4.185 0 0 0 0-5.9l-.05-.05a4.16 4.16 0 0 0-2.95-1.218c-.2 0-.401.02-.6.048a4.17 4.17 0 0 0-1.17-3.552A4.16 4.16 0 0 0 13.85 0m0 3.333a.84.84 0 0 0-.59.245L6.275 10.56a4.186 4.186 0 0 0 0 5.902 4.186 4.186 0 0 0 5.902 0L19.16 9.48a.835.835 0 0 0 0-1.18.835.835 0 0 0-1.18 0l-6.985 6.984a2.49 2.49 0 0 1-3.54 0 2.49 2.49 0 0 1 0-3.54l6.983-6.985a.835.835 0 0 0 0-1.18.84.84 0 0 0-.59-.245`})})}var wt=(0,J.lazy)(()=>u(()=>import(`./ToolResultCharts-DVYs8fEi.js`).then(e=>({default:e.ToolResultChart})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125]))),Tt=236,Et=260;function Dt({layout:e,parts:t=[]}){let n=E(),r=O(),i=(0,J.useMemo)(()=>new Intl.NumberFormat(r,{maximumFractionDigits:2}),[r]),a=(0,J.useMemo)(()=>dt(e,t,n(`@theorem.host.image`)),[e,t,n]),[o,s]=(0,J.useState)(null);if(!ft(e,a))return null;let{images:c,audio:l}=a;return(0,W.jsxs)(A,{gap:3,children:[(0,W.jsxs)(Ne,{minWidth:Et,children:[e.figures.map(e=>(0,W.jsx)(M,{children:(0,W.jsx)(Me,{title:e.label,value:ve(i.format(e.value),e.unit)})},`figure:${e.key}`)),e.charts.map(e=>(0,W.jsx)(J.Suspense,{fallback:(0,W.jsx)(M,{children:(0,W.jsx)(Ue,{height:Tt})}),children:(0,W.jsx)(M,{children:(0,W.jsx)(wt,{chart:e})})},`chart:${e.key}`)),c.map((e,t)=>(0,W.jsx)(M,{children:(0,W.jsx)(Je,{label:e.alt||`Open image`,padding:0,onClick:()=>s(t),children:(0,W.jsx)(ae,{ratio:4/3,fit:`cover`,children:(0,W.jsx)(`img`,{src:e.src,alt:e.alt,loading:`lazy`})})})},`image:${e.src}`))]}),c.length>0?(0,W.jsx)(qe,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:c.map(e=>({src:e.src,alt:e.alt})),index:o??0,onIndexChange:s}):null,te(l,e=>e.src).map(({item:e,key:t})=>(0,W.jsx)(M,{children:(0,W.jsx)(Ge,{src:e.src,mimeType:e.mimeType})},t))]})}function Ot({output:e,parts:t}){let n=E(),r=(0,J.useMemo)(()=>lt(e),[e]),i=(0,J.useMemo)(()=>r.figures.map(e=>e.key),[r]);return(0,W.jsx)(Ve,{value:e,title:n(`@theorem.host.response`),lead:(0,W.jsx)(Dt,{layout:r,parts:t}),ledKeys:i})}var kt=8,At={running:`accent`,background:`accent`,gate:`warning`,complete:`success`,error:`error`,cancel:`neutral`};function jt(e,t,n){let r;try{r=JSON.parse(n)}catch{return{ok:!1,note:e(`@theorem.decision.invalid_json`)}}if(!b(r))return{ok:!1,note:e(`@theorem.decision.invalid_json`)};let i=ue(t.inputSchema,r);return i.length>0?{ok:!1,note:e(`@theorem.host.missing`,{fields:i.join(`, `)}),input:r}:{ok:!0,input:r}}var Mt={function:ce,http:le,mcp:Ct},Nt=440,Pt=2;function Ft(e,t){let n=e(`@theorem.host.kind.${t.kind}`);return t.description?`${n} · ${t.description}`:n}function It({tool:e}){let t=E();return e.access===`read-only`?null:(0,W.jsx)(k,{gap:1,wrap:`wrap`,children:(0,W.jsx)(s,{label:t(`@theorem.tool.access.${e.access}`),size:`sm`,color:e.access===`destructive`?`red`:`orange`})})}function Lt(e,t,n){return{label:t.call?re(t.call):t.name,duration:t.isRunning?we(e,n-t.startedAt):t.elapsedMs==null?null:T(e,t.elapsedMs)}}function Y({call:e,onAnswer:t}){let n=e.call?.state;return n?.phase===`gate`?n.gate.kind===`auth`?(0,W.jsx)(g,{gate:n.gate,toolName:e.name,submitted:e.answering===`auth`,onAuthenticated:n=>void t(e.id,{action:`auth`,secret:n})}):(0,W.jsx)(oe,{gate:n.gate,toolName:e.name,input:e.input,decided:e.answering===`auth`?null:e.answering,onDecision:n=>void t(e.id,{action:n})}):null}function X(e){let t=e.call?.state;return!!q(e)||t?.phase===`complete`||!e.isRunning}function Z(e){let t=e.call?.state;return!X(e)&&t?.phase!==`gate`}function Rt({call:e,activity:t}){let n=e.call?.state,r=q(e);return(0,W.jsx)(Ie,{children:(0,W.jsxs)(A,{gap:3,children:[r?(0,W.jsx)(M,{children:(0,W.jsx)(Le,{status:`error`,role:`alert`,title:r.title,description:r.description})}):null,n?.phase===`complete`?(0,W.jsx)(Ot,{output:n.output,parts:n.parts}):null,e.isRunning?null:(0,W.jsx)(M,{children:t})]})})}function zt({call:e,onAnswer:t}){let n=E(),{label:r,duration:i}=Lt(n,e,Ce(e.isRunning));if(Z(e))return(0,W.jsx)(j,{label:r,since:e.startedAt});let a=(0,W.jsx)(l,{size:`sm`,color:`secondary`,children:i?n(`@theorem.host.finished`,{activity:r,duration:i}):r});return(0,W.jsxs)(A,{gap:3,children:[(0,W.jsx)(Y,{call:e,onAnswer:t}),X(e)?(0,W.jsx)(Rt,{call:e,activity:a}):null]})}function Bt({calls:e,onPick:t}){let n=E(),r=O(),i=(0,J.useMemo)(()=>new Intl.DateTimeFormat(r,{timeStyle:`medium`}),[r]);return e.length===0?null:(0,W.jsxs)(A,{gap:1,children:[(0,W.jsx)(l,{type:`supporting`,color:`secondary`,as:`h3`,children:n(`@theorem.host.earlier`)}),(0,W.jsx)(Te,{hasDividers:!0,density:`compact`,children:e.slice(0,kt).map(e=>{let r=vt(e);return(0,W.jsx)(Ee,{label:e.name,startContent:(0,W.jsx)(K,{variant:At[r],label:n(`@theorem.host.status.${r}`),isPulsing:e.isRunning}),endContent:(0,W.jsx)(l,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:i.format(e.startedAt)}),onClick:()=>t(e)},e.id)})})]})}function Vt({tools:e,tool:t,check:n,text:r,view:i,shown:a,onText:o,onPick:s,onView:c,onRun:u,onStop:d}){let f=E(),p=`input`in n?n.input:void 0,m=i===`fields`&&p!==void 0;return(0,W.jsxs)(Oe,{title:f(`@theorem.host.request`),view:m?`fields`:`json`,hasFields:p!==void 0,onView:c,onRun:u,children:[(0,W.jsxs)(A,{gap:2,children:[(0,W.jsx)(Ke,{label:f(`@theorem.host.tool`),size:`sm`,options:e.map(e=>({value:e.name,label:e.name,icon:Mt[e.kind],description:Ft(f,e)})),value:t.name,hasSearch:e.length>8,renderOption:e=>(0,W.jsx)(`div`,{style:{width:Nt,maxWidth:`100%`,minWidth:0},children:(0,W.jsx)(We,{icon:e.icon,label:e.label,description:e.description&&(0,W.jsx)(l,{type:`supporting`,color:`secondary`,maxLines:Pt,children:e.description})})}),onChange:s}),(0,W.jsx)(It,{tool:t})]}),m?(0,W.jsx)(Fe,{schema:t.inputSchema,value:p,onChange:e=>{o(S(e))}},t.name):(0,W.jsx)(Ae,{label:f(`@theorem.host.request`),text:r,isInvalid:p===void 0,onChange:o}),(0,W.jsx)(ke,{note:n.ok?f(`@theorem.host.shortcut`):n.note,isReady:n.ok,isRunning:a?.isRunning===!0,runLabel:f(`@theorem.host.run`),runningLabel:f(`@theorem.host.running`),stopLabel:f(`@theorem.host.stop`),onRun:u,onStop:()=>{a&&d(a.id)}})]})}function Ht(e,t,n,r){return!t||!n?.ok||r?.isRunning?null:e.run(t.name,n.input)}function Ut(e,t){let n=E(),[r,i]=(0,J.useState)(e.tools[0]?.name),[a,o]=(0,J.useState)({}),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(`fields`),{tool:d,text:f,shown:p,earlier:m}=yt({tools:e.tools,picked:r,drafts:a,calls:t.calls,shownId:s}),h=d?jt(n,d,f):null;return{tool:d,text:f,shown:p,earlier:m,check:h,view:l,setView:u,setPicked:i,setText:e=>{d&&o(t=>({...t,[d.name]:e}))},run:()=>{let e=Ht(t,d,h,p);e!==null&&c(e)},pick:e=>{i(e.name),o(t=>({...t,[e.name]:S(e.input)})),c(e.id)}}}function Wt({shown:e,earlier:t,onAnswer:n,onPick:r}){return(0,W.jsxs)(W.Fragment,{children:[e?(0,W.jsx)(zt,{call:e,onAnswer:n}):null,(0,W.jsx)(Bt,{calls:t,onPick:r})]})}function Gt(e,t,n,r,i){if(!e)return i;let a=r.length===0;return!n&&a?null:(0,W.jsx)(De,{label:t,fill:n!=null&&Z(n)&&a,children:i})}function Kt({transport:e,iface:t,host:n,maxWidth:r=`960px`,trace:i,flush:a,columns:o=!1,className:s,style:c}){let l=E(),u=Re(t,e.traces,i),d=Ut(t,n),{tool:f,check:p,shown:m,earlier:h}=d;return(0,W.jsxs)(je,{inspector:u,maxWidth:r,flush:a,columns:o,requestLabel:l(`@theorem.host.request`),className:s,style:c,children:[f&&p?(0,W.jsx)(Vt,{tools:t.tools,tool:f,check:p,text:d.text,view:d.view,shown:m,onText:d.setText,onPick:d.setPicked,onView:d.setView,onRun:d.run,onStop:n.cancel}):(0,W.jsx)(Se,{title:l(`@theorem.host.no_tools`)}),Gt(o,l(`@theorem.host.response`),m,h,(0,W.jsx)(Wt,{shown:m,earlier:h,onAnswer:n.answer,onPick:d.pick}))]})}function qt(e){let t=E(),n=St(e.transport,e.pageTools);return n.describeFailure?(0,W.jsx)(ze,{title:n.describeFailure.error}):n.iface?(0,W.jsx)(Kt,{...e,iface:n.iface,host:n}):(0,W.jsx)(j,{label:t(`@theorem.chat.loading`)})}function Jt({endpoint:e,http:t,transport:n,theme:r,mode:i,labels:a,detectCodeLanguage:o,...s}){let c=(0,J.useRef)(t);c.current=t;let l=(0,J.useMemo)(()=>n??h({...c.current,endpoint:e}),[n,e]);return(0,W.jsx)(p,{theme:r,mode:i,children:(0,W.jsx)(D,{labels:a,children:(0,W.jsx)(Be,{detectCodeLanguage:o,children:(0,W.jsx)(qt,{...s,transport:l})})})})}var Yt=e({HostView:()=>$,StudioHostConsole:()=>Q});function Q(e){let t=Pe(e,m,f);return(0,W.jsx)($,{...e,transport:t})}function $({payload:e,transport:t,trace:n,flush:r,columns:i,className:a}){let o=(0,J.useMemo)(()=>ie(e),[e]);return(0,W.jsx)(Jt,{detectCodeLanguage:!0,labels:_,transport:t,pageTools:o,trace:n,flush:r,columns:i,className:a})}export{$ as HostView,Q as StudioHostConsole,ht as n,Yt as t};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ToolResultCharts-Cx0g4QOl.js","assets/rolldown-runtime-hePW80VL.js","assets/themeProps-Bo2jNkIC.js","assets/Text-BDwNaqzZ.js","assets/mergeProps-ptS-gIMz.js","assets/useMergedRefs-BgzyWuff.js","assets/preload-helper-DpV6A1kQ.js","assets/shaped-data-CjB-teds.js","assets/host-patterns-F-KZIzkF.js","assets/TraceOverview-B2Q3oXth.js","assets/Icon-Cluq4EiW.js","assets/tokens.stylex-a4pw9QVe.js","assets/layerScopedContext-BA4VBuWG.js","assets/devWarning-DxuplmRl.js","assets/useMediaQuery-D0tQ79Tl.js","assets/useTooltip-ClCeZiOV.js","assets/padding.stylex-BWRTzhFl.js","assets/useLayerDismissal-7g2rAKDN.js","assets/useClickableContainer-dg6qYWze.js","assets/Button-98PahHB4.js","assets/focusOutline.stylex-LUQxyg0W.js","assets/usePressFeedback-BpX4yZ5R.js","assets/Spinner-B6MdidYQ.js","assets/VisuallyHidden-Dfmmn1_I.js","assets/CodeBlock-D7u2qG-t.js","assets/isRenderable-DHkzpAoQ.js","assets/rtlStyles-CVVETNV7.js","assets/useScrollableArea-CIrHdx_f.js","assets/focusableSelector-DXZeMU85.js","assets/IconButton-Jbcy-K-d.js","assets/useClipboard-CAtohmvr.js","assets/useAnnounce-QM3mmuiE.js","assets/highlightRanges-B7TRPq9q.js","assets/Tooltip-Dhy5lIDA.js","assets/row-keys-0Bn7ZyYy.js","assets/createReactComponent-DVEyVJ-p.js","assets/trace-record-CchShZYV.js","assets/labels-provider-9Mz_CB_a.js","assets/useTranslator-Ba7ULSHc.js","assets/useLocale-d7ARRGFj.js","assets/HStack-CqE4exX9.js","assets/Stack-De5MY0tq.js","assets/VStack-CCYGIv4A.js","assets/Card-DKuxiCN0.js","assets/container.stylex-CkS70he6.js","assets/index-CiwarrRR.js","assets/LayoutContent-ClBE78rU.js","assets/stackItem.stylex-BkECao56.js","assets/OverflowList-CDkPnQmt.js","assets/useDevWarning-WeXt8Pe8.js","assets/StackItem-ClAjT294.js","assets/plainDate-CE-glc6O.js","assets/useHighlightedOptionScroll-CFs91KPl.js","assets/fieldParts-DOfguMAs.js","assets/focusReturn-DF3Bi_HC.js","assets/isRtlElement-BG33-k_H.js","assets/FieldStatus-mbnJ60bK.js","assets/useIsHydrating-JHu3d-Y0.js","assets/Token-BZrQH6-I.js","assets/disabledInteraction-2qeNzu0m.js","assets/SidePanel-CYk_zksv.js","assets/ScrollableArea-BGmyGfiL.js","assets/TextInput-BRBEgg_h.js","assets/useBusyAnnouncement-CjJI13FX.js","assets/inputStyles.stylex-Dmh4r-B9.js","assets/InputClearButton-ClwCL3dr.js","assets/useResolvedRequired-DR7Agwbm.js","assets/CheckboxIndicator-Cca43Ctu.js","assets/useScrollLock-Dm92sJDr.js","assets/useFocusLeavingChange-Bb1WH0Lr.js","assets/useSettledOpen-DTsZ7A6A.js","assets/browser-transport-eZfjcJk5.js","assets/IconAlertTriangle-CL88MFAk.js","assets/compile-CmwVyRsa.js","assets/tool-schema-Cqelak6O.js","assets/schemas-D7cgkv3L.js","assets/tree-DoI5ABlX.js","assets/live-ingress-OuSlQ6q7.js","assets/browser-connection-D0GtrJxN.js","assets/schema-V9Rv344d.js","assets/types-yrvA7TCg.js","assets/Center-C9ai7fq_.js","assets/IconFilter-DYCjUyWk.js","assets/IconMicrophone-BT77cilC.js","assets/IconSearch-BN1R3FIx.js","assets/IconTool-BHps7rbl.js","assets/reader-CVIM-dZI.js","assets/trace-schema--4IGmLeE.js","assets/stub-CeHLNUXC.js","assets/registry-BpOBaSGc.js","assets/HoverCard-BaUeXNdO.js","assets/type-icons-DgazEJTc.js","assets/IconMathFunction-CyMTpj2z.js","assets/IconServer-Dfs13rbh.js","assets/IconWorld-DkkGLUyH.js","assets/studio-labels-BZWk1UYO.js","assets/turn-client-_TUC5_DY.js","assets/encode-files-DWBa8FAF.js","assets/Badge-Cj3D81QB.js","assets/CollapsibleGroup-D_hnA9UR.js","assets/project-address-DjxPZuyn.js","assets/workspace-BpNR3COy.js","assets/lent-keys-C32ems-I.js","assets/editors-BJX_S59A.js","assets/people-CIsR0-5R.js","assets/studio-session-ClF2iNCX.js","assets/useAnnounceRenderedText-_-FYc-5m.js","assets/EmptyState-DVoDGbtj.js","assets/use-second-ticker-ovc65-Bo.js","assets/use-second-ticker-D0uA9-ps.css","assets/CheckboxInput-nEEHX5M1.js","assets/menuBottomSheet.stylex-BoKs4EdV.js","assets/menuItemRoles-Bod0knkp.js","assets/useMenuPress-BHmqa9bx.js","assets/useMenuOverflow-nA_EuFZP.js","assets/typeaheadMatch-BJfmSQc6.js","assets/useFocusReturnVisibility-Brk7Chog.js","assets/useKeyboardHint-BP66YM6d.js","assets/PanelSearchInput-Dw5TVlEX.js","assets/ListItem-BevY6nJP.js","assets/MenuBottomSheetActionList-4BzDY0Sv.js","assets/LayoutFooter-QMRRAZfF.js","assets/Dialog-C2GP5P7V.js","assets/chainEventHandlers-C6ttXGfW.js","assets/index-YKE-6URE.css","assets/trace-patterns-DFMwRU00.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{d as n,l as r,r as i,u as a}from"./themeProps-Bo2jNkIC.js";import{t as o}from"./mergeProps-ptS-gIMz.js";import{t as s}from"./Token-BZrQH6-I.js";import{t as c}from"./isRenderable-DHkzpAoQ.js";import{t as l}from"./Text-BDwNaqzZ.js";import{t as u}from"./preload-helper-DpV6A1kQ.js";import{b as d,i as f,s as p,u as m,v as h}from"./browser-transport-eZfjcJk5.js";import{t as ee}from"./Tooltip-Dhy5lIDA.js";import{t as te}from"./row-keys-0Bn7ZyYy.js";import{_ as ne,f as re,g as ie,m as ae,n as oe,r as g,t as _,v as se}from"./studio-labels-BZWk1UYO.js";import{t as ce}from"./IconMathFunction-CyMTpj2z.js";import{t as le}from"./IconWorld-DkkGLUyH.js";import{l as ue,u as de}from"./tool-schema-Cqelak6O.js";import{_ as fe,a as v,b as y,c as b,f as pe,h as x,l as S,n as C,o as me,r as he,t as ge,v as _e,x as ve,y as w}from"./shaped-data-CjB-teds.js";import{C as ye,d as be,i as xe}from"./turn-client-_TUC5_DY.js";import{t as Se}from"./EmptyState-DVoDGbtj.js";import{t as Ce}from"./use-second-ticker-ovc65-Bo.js";import{i as we,l as T,n as E,t as D}from"./labels-provider-9Mz_CB_a.js";import{t as O}from"./useLocale-d7ARRGFj.js";import{t as k}from"./HStack-CqE4exX9.js";import{t as A}from"./VStack-CCYGIv4A.js";import{n as Te,t as Ee}from"./ListItem-BevY6nJP.js";import{a as De,i as Oe,o as ke,r as Ae,t as je}from"./ConsoleFrame-Dz65yVLC.js";import{i as Me}from"./trace-patterns-DFMwRU00.js";import{n as Ne,t as Pe}from"./studio-console-CCRqaMr7.js";import{t as Fe}from"./SchemaFields-D7UGra6l.js";import{B as Ie,D as Le,N as Re,O as ze,Q as Be,R as Ve,T as He,ft as Ue,ht as We,k as j,lt as Ge,pt as Ke,st as qe,ut as Je,z as M}from"./index-CiwarrRR.js";var Ye=4,Xe=3,Ze=3,N=8,Qe=6,P=3,$e=3,et=/(^|_)(id|ids|lat|lon|lng|latitude|longitude|offset|interval|index|rank|order)$|Id$|^(generationtime_ms|utc_offset_seconds)$/i,tt=/\.(png|jpe?g|gif|webp|avif|svg)$/i;function nt(e){if(/\s/.test(e))return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&tt.test(t.pathname)}catch{return!1}}function F(e){return!et.test(e)}function I(e){return/^[A-Z][A-Z0-9]{1,5}$/.test(e)?e:v(e)}function L(e,t){if(!F(e)||t&&e in t&&pe(t[e])===void 0)return;let{label:n,unit:r}=he(e,t);return{label:I(e)===e?e:n,unit:r}}function R(e,t){let n=[];for(let[r,i]of x(e)){if(typeof i!=`number`||!Number.isFinite(i))continue;let e=L(r,t);e&&n.push({key:r,value:i,...e})}return n.sort((e,t)=>Number(t.unit!==void 0)-Number(e.unit!==void 0)).slice(0,Ye)}function rt(e){if(!b(e))return[];for(let[t,n]of x(e)){let r=y(n);if(!b(r)||C(r))continue;let i=Object.values(r);if(i.length===0||!i.every(me))continue;let a=R(r,w(e,t));if(a.length>0)return a}return R(e,void 0)}function z(e,t){return new Set(e.map(e=>e[t])).size}function B(e,t,n){return[...new Set(e.flatMap(e=>Object.keys(e)))].filter(n=>n!==t&&e.every(e=>typeof e[n]==`number`||e[n]===null)&&z(e,n)>1).flatMap(e=>{let t=L(e,n);return t?[{key:e,...t}]:[]})}function it(e){let[t]=e;if(t)return Object.keys(t).find(t=>e.every(e=>typeof e[t]==`string`&&ge.test(e[t])))}function at(e){let t=e.map(e=>e.label.split(` `)),[n=[]]=t,r=0;for(;r<n.length&&t.every(e=>e.length>r+1&&e[r]===n[r]);)r++;if(r)return{title:n.slice(0,r).join(` `),series:e.map((e,n)=>{let i=(t[n]??[]).slice(r).join(` `);return{...e,label:i.charAt(0).toUpperCase()+i.slice(1)}})}}function ot(e,t,n,r,i){let a=new Map;for(let e of B(n,r,i)){let t=a.get(e.unit??``)??[];t.push(e),a.set(e.unit??``,t)}return[...a.values()].map(i=>{let a=i.slice(0,Ze),o=a.length>1?at(a):void 0;return{kind:`time`,key:`${e}:${a.map(e=>e.key).join(`+`)}`,title:a.length===1?a[0]?.label??t:o?.title??(t||a.map(e=>e.label).join(` · `)),x:r,series:o?.series??a,rows:n}})}function st(e){let[t]=e,n=t?_e(t):void 0;if(!t||!n||!e.every(e=>typeof e[n]==`string`||typeof e[n]==`number`))return;if(z(e,n)===e.length)return n;let r=t=>e.reduce((e,n)=>e+String(n[t]).length,0),[i]=Object.keys(t).filter(t=>e.every(e=>typeof e[t]==`string`)&&z(e,t)===e.length).sort((e,t)=>r(e)-r(t));return i??n}function ct(e,t,n,r){let i=st(n);return i?B(n,i,r).sort((e,t)=>z(n,t.key)-z(n,e.key)).map(r=>({kind:`category`,key:`${e}:${r.key}`,title:t?`${t} · ${r.label}`:r.label,series:r,rows:n.filter(e=>typeof e[r.key]==`number`).map(e=>({label:String(e[i]),value:e[r.key]})).sort((e,t)=>t.value-e.value).slice(0,N)})):[]}function V(e,t,n,r){if(n.length<P)return[];let i=it(n);return i?ot(e,t,n,i,r):ct(e,t,n,r)}function H(e,t,n,r,i){if(i>$e)return[];if(Array.isArray(e)){let i=e.map(y);return i.every(b)?V(t,n,i,r):[]}if(!b(e))return[];let a=C(e);if(a)return V(t,n,fe(e,a),r);let o=x(e),s=o.filter(([e,t])=>typeof t==`number`&&F(e));if(i>0&&s.length>=P&&s.length===o.length){let e=s.map(([e,t])=>({label:I(e),value:t}));return[{kind:`category`,key:t,title:n,series:{key:`value`,label:n},rows:e.sort((e,t)=>t.value-e.value).slice(0,N)}]}return o.flatMap(([r,a])=>H(y(a),t?`${t}.${r}`:r,i===0?v(r):`${n} › ${v(r)}`,w(e,r),i+1))}function U(e,t,n,r){if(r.size>=Qe||n>4)return;let i=y(e);if(typeof i==`string`)nt(i)&&!r.has(i)&&r.set(i,{src:i,alt:v(t||`image`)});else if(Array.isArray(i))for(let e of i)U(e,t,n+1,r);else if(b(i))for(let[e,t]of Object.entries(i))U(t,e,n+1,r)}function lt(e){let t=y(e),n=new Map;return U(t,``,0,n),{figures:rt(t),charts:H(t,``,``,void 0,0).slice(0,Xe),images:[...n.values()]}}function ut(e){return e.mimeType&&e.data?`data:${e.mimeType};base64,${e.data}`:void 0}function dt(e,t,n){let r=t.flatMap(e=>{let t=ut(e);return t?[{type:e.type,src:t,mimeType:e.mimeType}]:[]});return{images:[...r.filter(e=>e.type===`image`).map(({src:e})=>({src:e,alt:n})),...e.images],audio:r.filter(e=>e.type===`audio`).map(({src:e,mimeType:t})=>({src:e,...t?{mimeType:t}:{}}))}}function ft(e,t){return e.figures.length+e.charts.length+t.images.length+t.audio.length>0}var pt=864e5,mt=10;function ht(e){return e.some(e=>e.includes(`T`))?{tick:Math.abs(Date.parse(e.at(-1)??``)-Date.parse(e[0]??``))<=pt?{hour:`numeric`}:{month:`short`,day:`numeric`},when:{dateStyle:`medium`,timeStyle:`short`}}:{tick:e.length<=mt?{weekday:`short`,timeZone:`UTC`}:{month:`short`,day:`numeric`,timeZone:`UTC`},when:{dateStyle:`medium`,timeZone:`UTC`}}}var W=r(),G={base:{k1xSpc:`x3nfvp2`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,kaIpWk:`x16rqkct`,kmuXW:`x2lah0s`,kzqmXN:`x1xc55vz`,kZKoxP:`xdk7pt`,$$css:!0},pulsing:{kKVMdj:`x1mta51n`,k44tkh:`x1c74tu6`,kyAemX:`x4hg4is`,ko0y90:`xa4qsjk`,$$css:!0},reducedMotion:{kjO2d4:`x1aquc0h`,$$css:!0}},gt={success:{kWkggS:`xdsz4j9`,kMwMTN:`xri61p4`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},warning:{kWkggS:`x1q8g9m5`,kMwMTN:`xrebv38`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},error:{kWkggS:`x1pjz0fi`,kMwMTN:`x1m024r3`,kMeerF:`xcthrzx`,k3XXqK:`x815t2r`,kjBf7l:`x3teovq`,kInvED:`xvr1dqx`,$$css:!0},accent:{kWkggS:`x1ewilqj`,kMwMTN:`x17wrial`,$$css:!0},neutral:{kWkggS:`x1q5y3ey`,kMwMTN:`xrkvqaz`,$$css:!0}};function K({variant:e,label:t,isPulsing:n=!1,tooltip:r,icon:s,xstyle:l,className:u,style:d,ref:f,...p}){let m=c(s),h=(0,W.jsx)(`span`,{ref:f,role:`img`,"aria-label":t,...o(i(`status-dot`,{variant:e}),a(G.base,gt[e],n&&G.pulsing,n&&G.reducedMotion,l),u,d),...p,children:m&&(0,W.jsx)(`span`,{"aria-hidden":`true`,className:`x78zum5 x6s0dn4 xl56j7k x14ju556 x1xc55vz xdk7pt`,children:s})});return r?(0,W.jsx)(ee,{content:r,children:h}):h}K.displayName=`StatusDot`;var _t=new Set([`gate`,`background`,`complete`,`error`,`cancel`]);function vt({call:e,failure:t,isRunning:n}){let r=e?.state?.phase;return r!==void 0&&_t.has(r)?r:t?`error`:n?`running`:`cancel`}function q({call:e,failure:t}){if(t)return{title:t.error};let n=e?.state;if(n?.phase!==`error`)return null;let{error:r,message:i}=n.failure;return r?r===i?{title:r}:{title:r,description:i}:{title:i}}function yt(e){let t=e.tools.find(t=>t.name===e.picked)??e.tools[0],n=t?e.drafts[t.name]??S(de(t.inputSchema)):``,r=e.calls.filter(e=>e.name===t?.name),i=r.find(t=>t.id===e.shownId)??r[0]??null;return{tool:t,text:n,shown:i,earlier:e.calls.filter(e=>e!==i)}}var J=t(n(),1);function bt(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`call-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function xt(e,t){let n=[...e.events,t],r=t.type===`tool`&&t.tool.phase===`progress`?t.tool.data:e.progress;return{...e,events:n,call:ye(n)[0]??null,progress:r}}function St(e,t){let n=(0,J.useMemo)(()=>se(e,t),[e,t]),{iface:r,describeFailure:i}=He(n),[a,o]=(0,J.useState)([]),s=(0,J.useRef)(new Map),c=(0,J.useRef)([]),l=(0,J.useRef)(a);l.current=a,(0,J.useEffect)(()=>{let e=s.current;return()=>{for(let t of e.values())t.abort()}},[]);let u=(0,J.useCallback)((e,t)=>{o(n=>n.map(n=>n.id===e?t(n):n))},[]),f=(0,J.useCallback)(async(e,t)=>{let n=new AbortController;s.current.set(e,n);let r=performance.now();u(e,e=>({...e,isRunning:!0,failure:null}));try{await t(t=>{t.type!==`unsupported`&&t.type!==`malformed`&&u(e,e=>xt(e,t))},n.signal),u(e,e=>({...e,isRunning:!1,answering:null,elapsedMs:performance.now()-r}))}catch(t){let i=n.signal.aborted?null:d(t);u(e,e=>({...e,isRunning:!1,answering:null,failure:i,elapsedMs:performance.now()-r}))}finally{s.current.get(e)===n&&s.current.delete(e)}},[u]);return{iface:r,describeFailure:i,calls:a,run:(0,J.useCallback)((e,t)=>{let r=bt();return o(n=>[{id:r,name:e,input:t,events:[],call:null,progress:void 0,isRunning:!0,failure:null,answering:null,startedAt:Date.now(),elapsedMs:null},...n]),f(r,(r,i)=>n.call({name:e,input:t},r,i)),r},[f,n]),answer:(0,J.useCallback)(async(e,t)=>{let r=l.current.find(t=>t.id===e),i=r?.call?.state;if(!r?.call||i?.phase!==`gate`)return;let a=r.call.callId,o=xe(r.call),s=ne({toolName:r.name,gate:i.gate,sessionPermissions:c.current,resolution:t});s.decision===`approve`&&(c.current=s.sessionPermissions);let d=be(r.events);u(e,e=>({...e,answering:t.action})),await f(e,(e,t)=>n.invoke({gateId:a,operationId:o,decision:s.decision,...s.decision===`approve`&&s.secret!==void 0?{secret:s.secret}:{},replay:{name:r.name,input:i.gate.preparedArguments??r.input,gateKind:i.gate.kind,sessionPermissions:c.current,...d?{snapshot:d}:{}}},e,t))},[f,n,u]),cancel:(0,J.useCallback)(e=>{s.current.get(e)?.abort(),s.current.delete(e)},[])}}function Ct(e){return(0,W.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":!0,...e,children:(0,W.jsx)(`path`,{d:`M13.85 0a4.16 4.16 0 0 0-2.95 1.217L1.456 10.66a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l9.442-9.442a2.49 2.49 0 0 1 3.541 0 2.49 2.49 0 0 1 0 3.541L8.59 12.97l-.1.1a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l.1-.098 7.03-7.034a2.49 2.49 0 0 1 3.542 0l.049.05a2.49 2.49 0 0 1 0 3.54l-8.54 8.54a1.96 1.96 0 0 0 0 2.755l1.753 1.753a.835.835 0 0 0 1.18 0 .835.835 0 0 0 0-1.18l-1.753-1.753a.266.266 0 0 1 0-.394l8.54-8.54a4.185 4.185 0 0 0 0-5.9l-.05-.05a4.16 4.16 0 0 0-2.95-1.218c-.2 0-.401.02-.6.048a4.17 4.17 0 0 0-1.17-3.552A4.16 4.16 0 0 0 13.85 0m0 3.333a.84.84 0 0 0-.59.245L6.275 10.56a4.186 4.186 0 0 0 0 5.902 4.186 4.186 0 0 0 5.902 0L19.16 9.48a.835.835 0 0 0 0-1.18.835.835 0 0 0-1.18 0l-6.985 6.984a2.49 2.49 0 0 1-3.54 0 2.49 2.49 0 0 1 0-3.54l6.983-6.985a.835.835 0 0 0 0-1.18.84.84 0 0 0-.59-.245`})})}var wt=(0,J.lazy)(()=>u(()=>import(`./ToolResultCharts-Cx0g4QOl.js`).then(e=>({default:e.ToolResultChart})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125]))),Tt=236,Et=260;function Dt({layout:e,parts:t=[]}){let n=E(),r=O(),i=(0,J.useMemo)(()=>new Intl.NumberFormat(r,{maximumFractionDigits:2}),[r]),a=(0,J.useMemo)(()=>dt(e,t,n(`@theorem.host.image`)),[e,t,n]),[o,s]=(0,J.useState)(null);if(!ft(e,a))return null;let{images:c,audio:l}=a;return(0,W.jsxs)(A,{gap:3,children:[(0,W.jsxs)(Ne,{minWidth:Et,children:[e.figures.map(e=>(0,W.jsx)(M,{children:(0,W.jsx)(Me,{title:e.label,value:ve(i.format(e.value),e.unit)})},`figure:${e.key}`)),e.charts.map(e=>(0,W.jsx)(J.Suspense,{fallback:(0,W.jsx)(M,{children:(0,W.jsx)(Ue,{height:Tt})}),children:(0,W.jsx)(M,{children:(0,W.jsx)(wt,{chart:e})})},`chart:${e.key}`)),c.map((e,t)=>(0,W.jsx)(M,{children:(0,W.jsx)(Je,{label:e.alt||`Open image`,padding:0,onClick:()=>s(t),children:(0,W.jsx)(ae,{ratio:4/3,fit:`cover`,children:(0,W.jsx)(`img`,{src:e.src,alt:e.alt,loading:`lazy`})})})},`image:${e.src}`))]}),c.length>0?(0,W.jsx)(qe,{isOpen:o!==null,onOpenChange:e=>{e||s(null)},media:c.map(e=>({src:e.src,alt:e.alt})),index:o??0,onIndexChange:s}):null,te(l,e=>e.src).map(({item:e,key:t})=>(0,W.jsx)(M,{children:(0,W.jsx)(Ge,{src:e.src,mimeType:e.mimeType})},t))]})}function Ot({output:e,parts:t}){let n=E(),r=(0,J.useMemo)(()=>lt(e),[e]),i=(0,J.useMemo)(()=>r.figures.map(e=>e.key),[r]);return(0,W.jsx)(Ve,{value:e,title:n(`@theorem.host.response`),lead:(0,W.jsx)(Dt,{layout:r,parts:t}),ledKeys:i})}var kt=8,At={running:`accent`,background:`accent`,gate:`warning`,complete:`success`,error:`error`,cancel:`neutral`};function jt(e,t,n){let r;try{r=JSON.parse(n)}catch{return{ok:!1,note:e(`@theorem.decision.invalid_json`)}}if(!b(r))return{ok:!1,note:e(`@theorem.decision.invalid_json`)};let i=ue(t.inputSchema,r);return i.length>0?{ok:!1,note:e(`@theorem.host.missing`,{fields:i.join(`, `)}),input:r}:{ok:!0,input:r}}var Mt={function:ce,http:le,mcp:Ct},Nt=440,Pt=2;function Ft(e,t){let n=e(`@theorem.host.kind.${t.kind}`);return t.description?`${n} · ${t.description}`:n}function It({tool:e}){let t=E();return e.access===`read-only`?null:(0,W.jsx)(k,{gap:1,wrap:`wrap`,children:(0,W.jsx)(s,{label:t(`@theorem.tool.access.${e.access}`),size:`sm`,color:e.access===`destructive`?`red`:`orange`})})}function Lt(e,t,n){return{label:t.call?re(t.call):t.name,duration:t.isRunning?we(e,n-t.startedAt):t.elapsedMs==null?null:T(e,t.elapsedMs)}}function Y({call:e,onAnswer:t}){let n=e.call?.state;return n?.phase===`gate`?n.gate.kind===`auth`?(0,W.jsx)(g,{gate:n.gate,toolName:e.name,submitted:e.answering===`auth`,onAuthenticated:n=>void t(e.id,{action:`auth`,secret:n})}):(0,W.jsx)(oe,{gate:n.gate,toolName:e.name,input:e.input,decided:e.answering===`auth`?null:e.answering,onDecision:n=>void t(e.id,{action:n})}):null}function X(e){let t=e.call?.state;return!!q(e)||t?.phase===`complete`||!e.isRunning}function Z(e){let t=e.call?.state;return!X(e)&&t?.phase!==`gate`}function Rt({call:e,activity:t}){let n=e.call?.state,r=q(e);return(0,W.jsx)(Ie,{children:(0,W.jsxs)(A,{gap:3,children:[r?(0,W.jsx)(M,{children:(0,W.jsx)(Le,{status:`error`,role:`alert`,title:r.title,description:r.description})}):null,n?.phase===`complete`?(0,W.jsx)(Ot,{output:n.output,parts:n.parts}):null,e.isRunning?null:(0,W.jsx)(M,{children:t})]})})}function zt({call:e,onAnswer:t}){let n=E(),{label:r,duration:i}=Lt(n,e,Ce(e.isRunning));if(Z(e))return(0,W.jsx)(j,{label:r,since:e.startedAt});let a=(0,W.jsx)(l,{size:`sm`,color:`secondary`,children:i?n(`@theorem.host.finished`,{activity:r,duration:i}):r});return(0,W.jsxs)(A,{gap:3,children:[(0,W.jsx)(Y,{call:e,onAnswer:t}),X(e)?(0,W.jsx)(Rt,{call:e,activity:a}):null]})}function Bt({calls:e,onPick:t}){let n=E(),r=O(),i=(0,J.useMemo)(()=>new Intl.DateTimeFormat(r,{timeStyle:`medium`}),[r]);return e.length===0?null:(0,W.jsxs)(A,{gap:1,children:[(0,W.jsx)(l,{type:`supporting`,color:`secondary`,as:`h3`,children:n(`@theorem.host.earlier`)}),(0,W.jsx)(Te,{hasDividers:!0,density:`compact`,children:e.slice(0,kt).map(e=>{let r=vt(e);return(0,W.jsx)(Ee,{label:e.name,startContent:(0,W.jsx)(K,{variant:At[r],label:n(`@theorem.host.status.${r}`),isPulsing:e.isRunning}),endContent:(0,W.jsx)(l,{type:`supporting`,color:`secondary`,hasTabularNumbers:!0,children:i.format(e.startedAt)}),onClick:()=>t(e)},e.id)})})]})}function Vt({tools:e,tool:t,check:n,text:r,view:i,shown:a,onText:o,onPick:s,onView:c,onRun:u,onStop:d}){let f=E(),p=`input`in n?n.input:void 0,m=i===`fields`&&p!==void 0;return(0,W.jsxs)(Oe,{title:f(`@theorem.host.request`),view:m?`fields`:`json`,hasFields:p!==void 0,onView:c,onRun:u,children:[(0,W.jsxs)(A,{gap:2,children:[(0,W.jsx)(Ke,{label:f(`@theorem.host.tool`),size:`sm`,options:e.map(e=>({value:e.name,label:e.name,icon:Mt[e.kind],description:Ft(f,e)})),value:t.name,hasSearch:e.length>8,renderOption:e=>(0,W.jsx)(`div`,{style:{width:Nt,maxWidth:`100%`,minWidth:0},children:(0,W.jsx)(We,{icon:e.icon,label:e.label,description:e.description&&(0,W.jsx)(l,{type:`supporting`,color:`secondary`,maxLines:Pt,children:e.description})})}),onChange:s}),(0,W.jsx)(It,{tool:t})]}),m?(0,W.jsx)(Fe,{schema:t.inputSchema,value:p,onChange:e=>{o(S(e))}},t.name):(0,W.jsx)(Ae,{label:f(`@theorem.host.request`),text:r,isInvalid:p===void 0,onChange:o}),(0,W.jsx)(ke,{note:n.ok?f(`@theorem.host.shortcut`):n.note,isReady:n.ok,isRunning:a?.isRunning===!0,runLabel:f(`@theorem.host.run`),runningLabel:f(`@theorem.host.running`),stopLabel:f(`@theorem.host.stop`),onRun:u,onStop:()=>{a&&d(a.id)}})]})}function Ht(e,t,n,r){return!t||!n?.ok||r?.isRunning?null:e.run(t.name,n.input)}function Ut(e,t){let n=E(),[r,i]=(0,J.useState)(e.tools[0]?.name),[a,o]=(0,J.useState)({}),[s,c]=(0,J.useState)(null),[l,u]=(0,J.useState)(`fields`),{tool:d,text:f,shown:p,earlier:m}=yt({tools:e.tools,picked:r,drafts:a,calls:t.calls,shownId:s}),h=d?jt(n,d,f):null;return{tool:d,text:f,shown:p,earlier:m,check:h,view:l,setView:u,setPicked:i,setText:e=>{d&&o(t=>({...t,[d.name]:e}))},run:()=>{let e=Ht(t,d,h,p);e!==null&&c(e)},pick:e=>{i(e.name),o(t=>({...t,[e.name]:S(e.input)})),c(e.id)}}}function Wt({shown:e,earlier:t,onAnswer:n,onPick:r}){return(0,W.jsxs)(W.Fragment,{children:[e?(0,W.jsx)(zt,{call:e,onAnswer:n}):null,(0,W.jsx)(Bt,{calls:t,onPick:r})]})}function Gt(e,t,n,r,i){if(!e)return i;let a=r.length===0;return!n&&a?null:(0,W.jsx)(De,{label:t,fill:n!=null&&Z(n)&&a,children:i})}function Kt({transport:e,iface:t,host:n,maxWidth:r=`960px`,trace:i,flush:a,columns:o=!1,className:s,style:c}){let l=E(),u=Re(t,e.traces,i),d=Ut(t,n),{tool:f,check:p,shown:m,earlier:h}=d;return(0,W.jsxs)(je,{inspector:u,maxWidth:r,flush:a,columns:o,requestLabel:l(`@theorem.host.request`),className:s,style:c,children:[f&&p?(0,W.jsx)(Vt,{tools:t.tools,tool:f,check:p,text:d.text,view:d.view,shown:m,onText:d.setText,onPick:d.setPicked,onView:d.setView,onRun:d.run,onStop:n.cancel}):(0,W.jsx)(Se,{title:l(`@theorem.host.no_tools`)}),Gt(o,l(`@theorem.host.response`),m,h,(0,W.jsx)(Wt,{shown:m,earlier:h,onAnswer:n.answer,onPick:d.pick}))]})}function qt(e){let t=E(),n=St(e.transport,e.pageTools);return n.describeFailure?(0,W.jsx)(ze,{title:n.describeFailure.error}):n.iface?(0,W.jsx)(Kt,{...e,iface:n.iface,host:n}):(0,W.jsx)(j,{label:t(`@theorem.chat.loading`)})}function Jt({endpoint:e,http:t,transport:n,theme:r,mode:i,labels:a,detectCodeLanguage:o,...s}){let c=(0,J.useRef)(t);c.current=t;let l=(0,J.useMemo)(()=>n??h({...c.current,endpoint:e}),[n,e]);return(0,W.jsx)(p,{theme:r,mode:i,children:(0,W.jsx)(D,{labels:a,children:(0,W.jsx)(Be,{detectCodeLanguage:o,children:(0,W.jsx)(qt,{...s,transport:l})})})})}var Yt=e({HostView:()=>$,StudioHostConsole:()=>Q});function Q(e){let t=Pe(e,m,f);return(0,W.jsx)($,{...e,transport:t})}function $({payload:e,transport:t,trace:n,flush:r,columns:i,className:a}){let o=(0,J.useMemo)(()=>ie(e),[e]);return(0,W.jsx)(Jt,{detectCodeLanguage:!0,labels:_,transport:t,pageTools:o,trace:n,flush:r,columns:i,className:a})}export{$ as HostView,Q as StudioHostConsole,ht as n,Yt as t};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n,r,u as i}from"./themeProps-Bo2jNkIC.js";import{t as a}from"./mergeProps-ptS-gIMz.js";import{t as o}from"./Icon-Cluq4EiW.js";import{t as s}from"./Token-BZrQH6-I.js";import{t as c}from"./Text-BDwNaqzZ.js";import{t as l}from"./Button-98PahHB4.js";import{a as u,t as d}from"./TextInput-BRBEgg_h.js";import{w as f}from"./browser-transport-
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n,r,u as i}from"./themeProps-Bo2jNkIC.js";import{t as a}from"./mergeProps-ptS-gIMz.js";import{t as o}from"./Icon-Cluq4EiW.js";import{t as s}from"./Token-BZrQH6-I.js";import{t as c}from"./Text-BDwNaqzZ.js";import{t as l}from"./Button-98PahHB4.js";import{a as u,t as d}from"./TextInput-BRBEgg_h.js";import{w as f}from"./browser-transport-eZfjcJk5.js";import{t as p}from"./CodeBlock-D7u2qG-t.js";import{t as ee}from"./createReactComponent-DVEyVJ-p.js";import{Qt as te}from"./tool-schema-Cqelak6O.js";import{A as ne,Ar as m,Pr as h,Ur as g,a as _}from"./shaped-data-CjB-teds.js";import{k as v}from"./turn-client-_TUC5_DY.js";import{n as y}from"./stub-CeHLNUXC.js";import{t as re}from"./Badge-Cj3D81QB.js";import{n as b,t as x}from"./labels-provider-9Mz_CB_a.js";import{t as S}from"./HStack-CqE4exX9.js";import{t as ie}from"./VStack-CCYGIv4A.js";import{t as C}from"./Card-DKuxiCN0.js";import{n as w}from"./CollapsibleGroup-D_hnA9UR.js";var T=ee(`outline`,`flame`,`Flame`,[[`path`,{d:`M12 10.941c2.333 -3.308 .167 -7.823 -1 -8.941c0 3.395 -2.235 5.299 -3.667 6.706c-1.43 1.408 -2.333 3.294 -2.333 5.588c0 3.704 3.134 6.706 7 6.706c3.866 0 7 -3.002 7 -6.706c0 -1.712 -1.232 -4.403 -2.333 -5.588c-2.084 3.353 -3.257 3.353 -4.667 2.235`,key:`svg-0`}]]),E=[`cancelled`,`interrupted`,`length`,`filtered`,`provider_error`,`stream_incomplete`,`step_limit`],D=new Set(E);function O(e){return D.has(e)}function k(e,t,n){if(!e||!O(e.kind)||te(e)||t.some(e=>e.kind===`error`))return;let r=`stop.${e.kind}`;return g(r,{},n)}function A(e,t){let n=(n,r)=>{let i=new Set;return a=>{if(n(a),a.type!==`tool`||a.tool.phase!==`dispatch`)return;let{tool:o}=a;if(!e.pageResult||!o.operationId||r?.aborted)return;let s=JSON.stringify([o.operationId,o.grantId]);if(i.has(s))return;i.add(s);let c=t&&Object.hasOwn(t,o.name)?t[o.name]:void 0,l={callId:o.callId,operationId:o.operationId,grantId:o.grantId};Promise.resolve().then(async()=>{if(r?.aborted)return;let t=c?await Promise.resolve().then(()=>c(o.arguments,l)).catch(()=>({unanswered:!0})):{unanswered:!0};await e.pageResult?.({...l,page:t},r)}).catch(e=>{r?.aborted||n({type:`error`,errorKind:m(e),error:h(e)})})}},r=(e,t)=>{let r=n(e,t);return t=>t.type===`conversation`?e(t):r(t)};return`call`in e?{...e,describe:e.describe.bind(e),invoke:(t,r,i)=>e.invoke(t,n(r,i),i),call:(t,r,i)=>e.call(t,n(r,i),i)}:{...e,describe:e.describe.bind(e),invoke:(t,n,i)=>e.invoke(t,r(n,i),i),turn:(t,n,i)=>e.turn(t,r(n,i),i),steer:e.steer.bind(e),stop:e.stop.bind(e),conversation:e.conversation.bind(e),rewind:e.rewind.bind(e)}}function j(e){if(e.resolution.action===`deny`)return{decision:`deny`};let{resolution:t}=e;return{decision:`approve`,...t.action===`auth`&&t.secret!==void 0?{secret:t.secret}:{},...t.action===`page`?{page:t.page}:{},sessionPermissions:v(e.sessionPermissions,e.toolName,e.gate.permission)}}var M=`theorem.oauth_complete`;function N(e,t){if(e.source!==t.popup||e.origin!==t.origin)return!1;let n=e.data;return ne(n)&&n.type===M&&n.slot===t.slot}function P(e){return{openMessage:{type:`draft`,profile:e.profile,customTools:e.customTools}}}function F(e){let t={};for(let n of e.customTools){if(n.type!==`function`||n.answeredBy!==`page`)continue;let e=n.stubResponse??y(n.outputSchema);t[n.name]=()=>({output:e})}return t}var I=n(),L={container:{kVAEAm:`x1n2onr6`,kzqmXN:`xh8yej3`,kVQacm:`x7giv3`,kAzted:`x2lwn1j`,kmuXW:`x2lah0s`,$$css:!0},ellipse:{kaIpWk:`x16rqkct`,$$css:!0}},R={ratio:e=>[{kOBAk4:e==null?e:`x10y9f9r`,$$css:!0},{"--x-aspectRatio":e??void 0}]};function z({ratio:e,shape:t=`rectangle`,fit:n,children:o,xstyle:s,className:c,style:l,ref:u,...d}){return(0,I.jsx)(`div`,{ref:u,...a(r(`aspect-ratio`,{shape:t}),i(L.container,R.ratio(e),t===`ellipse`&&L.ellipse,s),c,l),...d,children:(0,I.jsx)(`div`,{"data-astryx-aspect-ratio-override":n,...{0:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d`},8:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k`},4:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq`},12:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq`},2:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x492jj3`},10:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x492jj3`},6:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x492jj3`},14:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x492jj3`},1:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x16lv2iq`},9:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x16lv2iq`},5:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x16lv2iq`},13:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x16lv2iq`},3:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x16lv2iq`},11:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k x16lv2iq`},7:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d xyz6fim x1m6kvgq x16lv2iq`},15:{className:`x10l6tqk x13vifvy x1o0tod xh8yej3 x5yr21d x78zum5 x6s0dn4 xl56j7k xyz6fim x1m6kvgq x16lv2iq`}}[(n===`center`)<<3|(n===`cover`||n===`contain`)<<2|(n===`cover`)<<1|n===`contain`],children:o})})}z.displayName=`AspectRatio`;function B(e,t){if(!e)return t;let n=e.total+t.total;return!e.cost&&!t.cost?{total:n}:{total:n,cost:{usd:(e.cost?.usd??0)+(t.cost?.usd??0),...!e.cost||!t.cost||e.cost.partial||t.cost.partial?{partial:!0}:{}}}}var V={citation:`last`};function H(e,t){if(!t)return[...e];let n=[],r=[],i=[];for(let a of e){let e=t[a.kind];e===`first`?n.push(a):e===`last`?i.push(a):r.push(a)}return[...n,...r,...i]}var U=new Set(E),W=new Set([`user-text`,`user-attachment`,`user-voice`]);function G(e){return W.has(e.kind)}function K(e){return e.kind===`turn-done`}function ae(e,t){e?.kind===`user`?t.stop&&U.has(t.stop.kind)&&(e.stop=t.stop):e&&(t.workedMs!==void 0&&(e.workedMs=t.workedMs,e.endedAt=t.endedAt),t.tokens&&(e.usage=B(e.usage,t.tokens)),t.stop&&(e.stop=t.stop))}function q(e,t){return!e||e.kind!==(t?`user`:`assistant`)?!1:!(e.kind===`user`&&e.stop)}function J(e,t){let n=[];for(let r of e){if(r.kind===`turn-done`&&ae(n.at(-1),r),K(r))continue;let e=G(r),i=n.at(-1);i&&q(i,e)&&!t?.has(r.id)?i.blocks.push(r):n.push({kind:e?`user`:`assistant`,key:r.id,blocks:[r]})}return n}function oe(e){return e.filter(e=>e.kind===`text`).map(e=>e.text).filter(Boolean).join(`
|
|
2
2
|
|
|
3
|
-
`)}function se(e){let t=e.elapsedMs===void 0?{}:{elapsedMs:e.elapsedMs};return e.streaming?{phase:`working`,...t}:e.elapsedMs!==void 0&&e.elapsedMs>0?{phase:`worked`,elapsedMs:e.elapsedMs}:e.hasTrace?{phase:`worked`}:null}function ce(e){return e.kind===`tool`&&e.tool.state?.phase===`gate`}function le(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.kind===`tool`)return t;return-1}function ue(e,t,n,r){t.hasTools&&t.index<t.lastToolIndex?e.text.trim()&&n.push({kind:`narration`,id:e.id,text:e.text}):r.push(e)}function de(e,t,n,r){e.kind===`thought`?e.text.trim()&&n.push({kind:`reasoning`,id:e.id,text:e.text}):e.kind===`tool`?n.push({kind:`tool`,id:e.id,block:e}):e.kind===`text`?ue(e,t,n,r):r.push(e)}function fe(e,t){let n=e.filter(e=>!K(e)),r=n.find(ce),i=r?[r]:[],a=n.filter(e=>e!==r),o=le(a),s=o>=0,c=[],l=[];for(let[e,t]of a.entries())de(t,{hasTools:s,index:e,lastToolIndex:o},c,l);return{trace:c,gatedTools:i,body:H(l,t?.bodyKindPlacement??V),hasTrace:c.length>0}}function pe(e){let t=e.at(-1);return t?.kind===`user`?t:void 0}function Y(e,t){let n=e[t-1];return n?.kind===`user`?X(n):e[t]?.key??String(t)}function X(e){return`${e.key}:reply`}function me(e,t,n){let r=e[t+1];return r?.kind===`assistant`&&r.endedAt!==void 0&&r.workedMs!==void 0?r.endedAt-r.workedMs:n(e[t]?.key??``)}function he(e){let t=Y(e.groups,e.index),n=e.streaming&&e.index===e.groups.length-1,r=e.groups[e.index];if(!n)return r?.kind===`assistant`&&r.workedMs!==void 0?{key:t,live:n,workedMs:r.workedMs,endedAt:r.endedAt}:{key:t,live:n};let i=e.groups[e.index-1],a=i?.kind===`user`?e.spans.get(i.key):void 0;return!i||!a?{key:t,live:n}:{key:t,live:n,startedAt:e.timeOf(i.key)+a.pausedMs}}function ge(e){let t=e.state?.phase;return t===`cancel`?_(e.name):(t===`complete`||t===`error`?e.activityPast:e.activity)??_(e.name)}var Z=e(t(),1);function _e(e,t,n,r){let i=t.request??e(`@theorem.gate.approval.use_tool`,{tool:_(n).toLowerCase()});return r?e(`@theorem.gate.approval.title`,{agent:r,request:i}):e(`@theorem.gate.approval.title_no_agent`,{request:i})}function
|
|
3
|
+
`)}function se(e){let t=e.elapsedMs===void 0?{}:{elapsedMs:e.elapsedMs};return e.streaming?{phase:`working`,...t}:e.elapsedMs!==void 0&&e.elapsedMs>0?{phase:`worked`,elapsedMs:e.elapsedMs}:e.hasTrace?{phase:`worked`}:null}function ce(e){return e.kind===`tool`&&e.tool.state?.phase===`gate`}function le(e){for(let t=e.length-1;t>=0;--t)if(e[t]?.kind===`tool`)return t;return-1}function ue(e,t,n,r){t.hasTools&&t.index<t.lastToolIndex?e.text.trim()&&n.push({kind:`narration`,id:e.id,text:e.text}):r.push(e)}function de(e,t,n,r){e.kind===`thought`?e.text.trim()&&n.push({kind:`reasoning`,id:e.id,text:e.text}):e.kind===`tool`?n.push({kind:`tool`,id:e.id,block:e}):e.kind===`text`?ue(e,t,n,r):r.push(e)}function fe(e,t){let n=e.filter(e=>!K(e)),r=n.find(ce),i=r?[r]:[],a=n.filter(e=>e!==r),o=le(a),s=o>=0,c=[],l=[];for(let[e,t]of a.entries())de(t,{hasTools:s,index:e,lastToolIndex:o},c,l);return{trace:c,gatedTools:i,body:H(l,t?.bodyKindPlacement??V),hasTrace:c.length>0}}function pe(e){let t=e.at(-1);return t?.kind===`user`?t:void 0}function Y(e,t){let n=e[t-1];return n?.kind===`user`?X(n):e[t]?.key??String(t)}function X(e){return`${e.key}:reply`}function me(e,t,n){let r=e[t+1];return r?.kind===`assistant`&&r.endedAt!==void 0&&r.workedMs!==void 0?r.endedAt-r.workedMs:n(e[t]?.key??``)}function he(e){let t=Y(e.groups,e.index),n=e.streaming&&e.index===e.groups.length-1,r=e.groups[e.index];if(!n)return r?.kind===`assistant`&&r.workedMs!==void 0?{key:t,live:n,workedMs:r.workedMs,endedAt:r.endedAt}:{key:t,live:n};let i=e.groups[e.index-1],a=i?.kind===`user`?e.spans.get(i.key):void 0;return!i||!a?{key:t,live:n}:{key:t,live:n,startedAt:e.timeOf(i.key)+a.pausedMs}}function ge(e){let t=e.state?.phase;return t===`cancel`?_(e.name):(t===`complete`||t===`error`?e.activityPast:e.activity)??_(e.name)}var Z=e(t(),1);function _e(e,t,n,r){let i=t.request??e(`@theorem.gate.approval.use_tool`,{tool:_(n).toLowerCase()});return r?e(`@theorem.gate.approval.title`,{agent:r,request:i}):e(`@theorem.gate.approval.title_no_agent`,{request:i})}var ve={outline:`none`};function ye(e){return typeof e==`string`?e:e==null?``:JSON.stringify(e,null,2)}function Q(e){return(0,I.jsx)(C,{variant:`bubble`,elevation:`med`,maxWidth:400,children:(0,I.jsxs)(ie,{gap:3,children:[(0,I.jsxs)(S,{justify:`between`,align:`start`,gap:3,children:[(0,I.jsx)(c,{type:`large`,weight:`semibold`,tabIndex:-1,"data-autofocus":!0,style:ve,children:e.heading}),e.tag]}),e.children]})})}var be={"read-only":u,"read-write":f,destructive:T};function $({access:e}){let t=b();return(0,I.jsxs)(S,{gap:1,align:`center`,children:[(0,I.jsx)(o,{icon:be[e],size:`sm`,color:e===`destructive`?`error`:`secondary`}),(0,I.jsx)(c,{type:`supporting`,textWrap:`nowrap`,children:t(`@theorem.tool.access.${e}`)})]})}function xe(e){return(0,I.jsx)(x,{children:(0,I.jsx)(Se,{...e})})}function Se({gate:e,toolName:t,agent:n,input:r,decided:i=null,onDecision:a}){let o=b(),s=ye(e.preparedArguments??r);return(0,I.jsxs)(Q,{heading:_e(o,e,t,n),tag:e.access?(0,I.jsx)($,{access:e.access}):null,children:[e.summary?(0,I.jsx)(c,{color:`secondary`,children:e.summary}):null,s?(0,I.jsx)(w,{defaultIsOpen:!1,trigger:(0,I.jsx)(c,{type:`supporting`,children:o(`@theorem.gate.approval.input`)}),children:(0,I.jsx)(p,{code:s,language:`json`,size:`sm`})}):null,(0,I.jsxs)(S,{gap:2,justify:`end`,children:[(0,I.jsx)(l,{label:o(`@theorem.gate.approval.deny`),variant:`ghost`,isLoading:i===`deny`,isDisabled:i===`allow`,onClick:()=>a?.(`deny`)}),(0,I.jsx)(l,{label:o(`@theorem.gate.approval.approve`),variant:`primary`,isLoading:i===`allow`,isDisabled:i===`deny`,onClick:()=>a?.(`allow`)})]})]})}function Ce({challenge:e}){let t=b();return(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(c,{color:`secondary`,children:e.message}),e.resource?(0,I.jsx)(c,{type:`supporting`,color:`secondary`,children:t(`@theorem.gate.auth.resource`,{resource:e.resource})}):null,e.requiredScopes?.length?(0,I.jsx)(S,{gap:1,wrap:`wrap`,children:e.requiredScopes.map(e=>(0,I.jsx)(s,{label:e,size:`sm`},e))}):null]})}function we(e){return(0,I.jsx)(x,{children:(0,I.jsx)(Ee,{...e})})}function Te(e,t){let[n,r]=(0,Z.useState)(null);return(0,Z.useEffect)(()=>{if(!n)return;function i(i){n&&N(i,{popup:n,slot:e,origin:globalThis.location.origin})&&(r(null),t())}return globalThis.addEventListener(`message`,i),()=>globalThis.removeEventListener(`message`,i)},[n,e,t]),e=>r(globalThis.open(e,`_blank`,`width=600,height=700`))}function Ee({gate:e,toolName:t,onAuthenticated:n,submitted:r=!1}){let i=b(),a=e.authChallenge,{authType:o,slot:s}=a,[l,u]=(0,Z.useState)(``),d=Te(s,(0,Z.useCallback)(()=>n?.(),[n]));function f(){let e=l.trim();e&&(u(``),n?.(e))}return(0,I.jsxs)(Q,{heading:i(`@theorem.gate.auth.title`,{tool:_(t).toLowerCase()}),tag:(0,I.jsx)(c,{type:`supporting`,textWrap:`nowrap`,children:i(`@theorem.gate.tag.${o}`)}),children:[(0,I.jsx)(Ce,{challenge:a}),(0,I.jsx)(De,{authType:o,authUrl:a.authorizationUrl,slot:s,secret:l,submitted:r,onSecretChange:u,onSubmit:f,onOpenSignIn:d})]})}function De(e){let t=b();if(e.submitted)return(0,I.jsx)(re,{variant:`success`,label:t(`@theorem.gate.auth.provided`,{slot:e.slot})});if(e.authType===`oauth2`)return e.authUrl?(0,I.jsx)(S,{justify:`end`,children:(0,I.jsx)(l,{label:t(`@theorem.gate.auth.authorize`),variant:`primary`,onClick:()=>{e.authUrl&&e.onOpenSignIn(e.authUrl)}})}):(0,I.jsx)(c,{color:`secondary`,children:t(`@theorem.gate.auth.no_oauth`)});let n=t(e.authType===`api_key`?`@theorem.gate.auth.api_key`:`@theorem.gate.auth.bearer`),r=t(`@theorem.gate.auth.secret_note`).trim();return(0,I.jsxs)(S,{gap:2,align:`end`,children:[(0,I.jsx)(d,{type:`password`,label:n,...r?{description:r}:{},value:e.secret,placeholder:t(`@theorem.gate.auth.secret_placeholder`,{slot:e.slot}),autoComplete:`off`,onChange:e.onSecretChange,onEnter:e.onSubmit,width:`100%`}),(0,I.jsx)(l,{label:t(`@theorem.gate.auth.submit`),variant:`primary`,isDisabled:!e.secret.trim(),onClick:e.onSubmit})]})}var Oe={en:{"@theorem.gate.auth.secret_note":`Used for this call only. theorem doesn't store it.`,"@astryx.chat.status.sending":`sending`,"@astryx.chat.status.sent":`sent`,"@astryx.chat.status.delivered":`delivered`,"@astryx.chat.status.read":`read`}};export{j as _,he as a,T as b,pe as c,Y as d,ge as f,F as g,P as h,oe as i,X as l,z as m,xe as n,fe as o,se as p,we as r,J as s,Oe as t,me as u,A as v,k as y};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-ClBE78rU.js";import{t as a}from"./StackItem-ClAjT294.js";import{t as o}from"./Icon-Cluq4EiW.js";import{a as s,c,l,p as u,u as d}from"./SidePanel-CYk_zksv.js";import{t as f}from"./Text-BDwNaqzZ.js";import{t as p}from"./Button-98PahHB4.js";import{b as m,g as h,p as g,s as _,t as v}from"./browser-transport-CbYs8r-W.js";import{t as y}from"./createReactComponent-DVEyVJ-p.js";import{t as b}from"./Center-C9ai7fq_.js";import{_ as x,g as S,h as C,m as w,n as T,r as E,t as ee}from"./studio-labels-B-e0Wofl.js";import{t as te}from"./IconMicrophone-BT77cilC.js";import{c as D}from"./host-patterns-F-KZIzkF.js";import{Or as O,Ur as k,or as A,sr as j}from"./shaped-data-CjB-teds.js";import{S as M,g as N,r as P,t as F}from"./reader-CVIM-dZI.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as ne,y as re}from"./turn-client-_TUC5_DY.js";import{r as ie,t as ae}from"./live-messages-Cfo-A3Ia.js";import{t as oe}from"./EmptyState-DVoDGbtj.js";import"./use-second-ticker-ovc65-Bo.js";import{a as se,n as L,t as R}from"./labels-provider-DfcbklTS.js";import{t as z}from"./HStack-CqE4exX9.js";import{t as B}from"./IconButton-Jbcy-K-d.js";import{t as V}from"./VStack-CCYGIv4A.js";import{t as ce}from"./Toolbar-CE6Lf31u.js";import{t as le}from"./Dialog-C2GP5P7V.js";import{Bt as ue,D as H,H as U,Ht as de,L as fe,M as W,N as pe,Nt as me,Vt as he,Zt as ge,_t as _e,ct as ve,l as ye,w as be,y as xe}from"./index-D2y4CjDY.js";var Se=y(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),Ce=y(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),we=y(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Te=y(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),G=y(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ee=y(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),De=y(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),K=y(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Oe(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function ke(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Ae(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function je(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var q=new Set;async function Me(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!q.has(n)&&(q.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Ne(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Pe=`mic-capture-processor`;function Fe(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Ie(e,t,n=16e3){if(t===n)return Le(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=Re(i>0?n/i:0),o++,s=t}return a}function Le(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=Re(e[n]??0);return t}function Re(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new D(`internal`,O(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=ue(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return ke({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new D(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new D(`network`,`live call dropped and could not reconnect`)),this.lostAt=e}else this.reconnectTries+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.open(`reconnecting`)},e)}failOpen(e){this.status===`reconnecting`?(this.teardownConnection(),this.scheduleReconnect()):this.startOver()||this.failSession(e)}async open(e){this.teardownConnection(),this.sessionOver=!1,this.setStatus(e),e===`connecting`&&this.setConnectPhase(`socket`);try{let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume();let t=globalThis.location.protocol===`https:`?`wss:`:`ws:`,n=this.options.profile?`?profile=${encodeURIComponent(this.options.profile)}`:``,r=`${t}//${globalThis.location.host}/api/live/relay${n}`,i=this.options.relayUrl||r;this.ws=this.createSocket(i),this.ws.binaryType=`arraybuffer`,this.ws.onopen=()=>{let e=this.openMessage();this.sentContext=JSON.stringify(e.context),this.ws?.send(JSON.stringify(e))},this.connectTimeout=setTimeout(()=>{this.opening&&this.failOpen(new D(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new D(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new D(`network`,`live socket error`))}}catch(e){this.failOpen(new D(`internal`,O(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Ne(e);this.failSession(new D(t?`auth`:`internal`,O(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Ie(e,t,16e3),r=j(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(he(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Fe()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Pe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(de(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Me({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:ne(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=ie(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(e.body,`request`)):e.status===`dispatched`?t.resolve({status:`dispatched`,grantId:e.grantId,arguments:e.arguments}):e.status===`gated`?t.resolve({status:`gated`,gate:e.gate}):t.resolve({status:`settled`}))}async tryHandleControlEnvelope(e){return e.type===`ready`?(await this.handleReadyEnvelope(e),!0):e.type===`executeToolResult`?(this.handleExecuteToolResultEnvelope(e),!0):e.type===`trace`?(this.options.onTrace?.(e.record),!0):e.type===`error`&&(this.startOver()||(this.sessionOver=!0,this.options.onError?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:je(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Ae(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new D(`request`,`live session is not connected`);let n=ae.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new D(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new D(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Je(e,t){return t.length===0?e:[...e,[...t]]}function Ye(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?re(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&ot(t.text,e.text))})}function ct(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{n as r,t as i}from"./LayoutContent-ClBE78rU.js";import{t as a}from"./StackItem-ClAjT294.js";import{t as o}from"./Icon-Cluq4EiW.js";import{a as s,c,l,p as u,u as d}from"./SidePanel-CYk_zksv.js";import{t as f}from"./Text-BDwNaqzZ.js";import{t as p}from"./Button-98PahHB4.js";import{b as m,g as h,p as g,s as _,t as v}from"./browser-transport-eZfjcJk5.js";import{t as y}from"./createReactComponent-DVEyVJ-p.js";import{t as b}from"./Center-C9ai7fq_.js";import{_ as x,g as S,h as C,m as w,n as T,r as E,t as ee}from"./studio-labels-BZWk1UYO.js";import{t as te}from"./IconMicrophone-BT77cilC.js";import{c as D}from"./host-patterns-F-KZIzkF.js";import{Or as O,Ur as k,or as A,sr as j}from"./shaped-data-CjB-teds.js";import{S as M,g as N,r as P,t as F}from"./reader-CVIM-dZI.js";import{i as I}from"./live-ingress-OuSlQ6q7.js";import{i as ne,y as re}from"./turn-client-_TUC5_DY.js";import{r as ie,t as ae}from"./live-messages-Cfo-A3Ia.js";import{t as oe}from"./EmptyState-DVoDGbtj.js";import"./use-second-ticker-ovc65-Bo.js";import{a as se,n as L,t as R}from"./labels-provider-9Mz_CB_a.js";import{t as z}from"./HStack-CqE4exX9.js";import{t as B}from"./IconButton-Jbcy-K-d.js";import{t as V}from"./VStack-CCYGIv4A.js";import{t as ce}from"./Toolbar-DAp_Uw5z.js";import{t as le}from"./Dialog-C2GP5P7V.js";import{Bt as ue,D as H,H as U,Ht as de,L as fe,M as W,N as pe,Nt as me,Vt as he,Zt as ge,_t as _e,ct as ve,l as ye,w as be,y as xe}from"./index-CiwarrRR.js";var Se=y(`outline`,`arrows-diagonal-minimize-2`,`ArrowsDiagonalMinimize2`,[[`path`,{d:`M18 10h-4v-4`,key:`svg-0`}],[`path`,{d:`M20 4l-6 6`,key:`svg-1`}],[`path`,{d:`M6 14h4v4`,key:`svg-2`}],[`path`,{d:`M10 14l-6 6`,key:`svg-3`}]]),Ce=y(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),we=y(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Te=y(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),G=y(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ee=y(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),De=y(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),K=y(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Oe(e){return e.status===`reconnecting`?`reconnecting`:e.toolName?`calling_tool`:e.connectPhase===`socket`?`connecting`:e.connectPhase===`microphone`?`requesting_mic`:e.status===`speaking`?`speaking`:e.status===`listening`||e.status===`ready`?e.voiceEnabled===!1?`connected`:e.isMuted?`muted`:`listening`:e.status===`connecting`?`connecting`:e.status===`error`?`error`:`ended`}function ke(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Ae(e){let{evidence:t,text:n}=e;return!n||t.kind!==`input_transcription`&&t.kind!==`output_transcription`?null:{text:n,isUser:t.kind===`input_transcription`,interim:t.interim===!0}}function je(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var q=new Set;async function Me(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!q.has(n)&&(q.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function Ne(e){if(!(e instanceof Error))return!1;let t=`name`in e&&typeof e.name==`string`?e.name:``;return t===`NotAllowedError`||t===`PermissionDeniedError`||/permission|not allowed|denied/i.test(e.message)}var Pe=`mic-capture-processor`;function Fe(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Ie(e,t,n=16e3){if(t===n)return Le(e);let r=t/n,i=Math.round(e.length/r),a=new Int16Array(i),o=0,s=0;for(;o<a.length;){let t=Math.round((o+1)*r),n=0,i=0;for(let r=s;r<t&&r<e.length;r++)n+=e[r]??0,i++;a[o]=Re(i>0?n/i:0),o++,s=t}return a}function Le(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=Re(e[n]??0);return t}function Re(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function ze(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function J(e){return JSON.stringify(e)}function Be(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ve=.05,He=[500,1e3,2e3,4e3,8e3];function Y(e){return e instanceof Error?e:new D(`internal`,O(e),{cause:e})}function X(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ue(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function We(e){let t=ue(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return ke({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ve})}function Ge(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Ke=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new D(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{options:e,stated:t,model:n,effort:r,openMessage:i}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{options:e}:{},...t?{stated:t}:{},...n?{model:n}:{},...r?{effort:r}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...i?{host:i}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=He[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new D(`network`,`live call dropped and could not reconnect`)),this.lostAt=e}else this.reconnectTries+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.open(`reconnecting`)},e)}failOpen(e){this.status===`reconnecting`?(this.teardownConnection(),this.scheduleReconnect()):this.startOver()||this.failSession(e)}async open(e){this.teardownConnection(),this.sessionOver=!1,this.setStatus(e),e===`connecting`&&this.setConnectPhase(`socket`);try{let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume();let t=globalThis.location.protocol===`https:`?`wss:`:`ws:`,n=this.options.profile?`?profile=${encodeURIComponent(this.options.profile)}`:``,r=`${t}//${globalThis.location.host}/api/live/relay${n}`,i=this.options.relayUrl||r;this.ws=this.createSocket(i),this.ws.binaryType=`arraybuffer`,this.ws.onopen=()=>{let e=this.openMessage();this.sentContext=JSON.stringify(e.context),this.ws?.send(JSON.stringify(e))},this.connectTimeout=setTimeout(()=>{this.opening&&this.failOpen(new D(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new D(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new D(`network`,`live socket error`))}}catch(e){this.failOpen(new D(`internal`,O(e),{cause:e}))}}async ensureAudioContext(){if(!this.audioContext||this.audioContext.state===`closed`){let e=globalThis.AudioContext;this.audioContext=new e,this.audioContext.state===`suspended`&&await this.audioContext.resume()}}async activateMicrophone(){if(!this.micActivating&&this.opening){this.micActivating=!0,this.status===`connecting`&&this.setConnectPhase(`microphone`);try{await this.ensureAudioContext(),this.micStream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}),await this.setupMicrophonePipeline(),this.becomeReady()}catch(e){let t=Ne(e);this.failSession(new D(t?`auth`:`internal`,O(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Ie(e,t,16e3),r=j(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(J({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(he(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),We({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(Fe()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Pe),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(de(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>Me({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs:e.arguments,callId:e.id,operationId:ne(e)})).catch(e=>{this.options.onError?.(Y(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=ie(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(Y(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(M(e.body,`request`)):e.status===`dispatched`?t.resolve({status:`dispatched`,grantId:e.grantId,arguments:e.arguments}):e.status===`gated`?t.resolve({status:`gated`,gate:e.gate}):t.resolve({status:`settled`}))}async tryHandleControlEnvelope(e){return e.type===`ready`?(await this.handleReadyEnvelope(e),!0):e.type===`executeToolResult`?(this.handleExecuteToolResultEnvelope(e),!0):e.type===`trace`?(this.options.onTrace?.(e.record),!0):e.type===`error`&&(this.startOver()||(this.sessionOver=!0,this.options.onError?.(M(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Be();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:je(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Ae(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ge(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(Y(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new D(`request`,`live session is not connected`);let n=ae.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new D(`request`,k(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new D(`request`,k(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(J(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(Y(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=A(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=ze(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(Y(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`text`,text:e}))}setOptions(e){JSON.stringify(e)!==JSON.stringify(this.options.options)&&(this.options={...this.options,options:e},this.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(J({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(J({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),X(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,X(this.micWorklet),null),X(this.micSource),this.micSource=null,Ue(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},Z=e(t(),1);function qe(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function Je(e,t){return t.length===0?e:[...e,[...t]]}function Ye(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:Xe(e,t):e:t}function Xe(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function Ze(e){return`${String(Date.now())}-${String(e.turns.length)}`}function Qe(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:Xe(s.text,t)};else{let n=i?.forceNew?t:Ye(c,t);o.push({id:Ze(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function $e(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function et(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function tt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:et(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function nt(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!$e(t))return e;let n=tt(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:Ze(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function rt(e){return e.role===`work`?re(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var it=24;function at(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ot(e,t){let n=e.trim();return at(n,t.trim())>=Math.min(n.length,it)}function st(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&ot(t.text,e.text))})}function ct(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>st(e).flatMap(rt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function lt({working:e,interimAgent:t}){return t!==``||e}function ut(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function dt(e,t){let n=Object.keys(t??{}).sort().join(`
|
|
2
2
|
`),r=e?.join(`
|
|
3
3
|
`);(0,Z.useEffect)(()=>{r!==void 0&&me(r?r.split(`
|
|
4
4
|
`):[],n?n.split(`
|
|
5
|
-
`):[])},[r,n])}var ft=.62,pt=400;function mt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function ht(e,t){let n=t?.facingMode??`user`;return mt(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new D(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,ft).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,pt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await mt(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function gt(e){let t=(0,Z.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,Z.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,Z.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>Qe(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Z.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await ht(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,Z.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,Z.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,Z.useCallback)(async()=>{t(),await n()},[n,t])}}function _t(e){return new N(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function vt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Q(t):e.phase===`error`?(t.reportFailure(_t(e.failure)),Q(t)):t.setActiveTool(e.name)}function yt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&vt(e.tool,t)}function bt(e){let[t,n]=(0,Z.useState)(`disconnected`),[r,i]=(0,Z.useState)(null),a=(0,Z.useRef)({input:0,output:0}),o=(0,Z.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Z.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(qe),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)([]),[ee,te]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(`user`),j=(0,Z.useRef)(null),M=(0,Z.useRef)(h),N=(0,Z.useRef)(c),P=(0,Z.useRef)(T),F=(0,Z.useRef)(t);return M.current=h,N.current=c,P.current=T,F.current=t,(0,Z.useEffect)(()=>{C&&te(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:f,setActiveTool:p,captions:h,setCaptions:g,failure:_,reportFailure:(0,Z.useCallback)(t=>{v(m(t,e))},[e]),clearFailure:(0,Z.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Z.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Z.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:E,everConnected:ee,videoPreview:D,setVideoPreview:O,videoFacingMode:k,setVideoFacingMode:A,videoCaptureRef:j,captionsRef:M,isMutedRef:N,sessionPermissionsRef:P,statusRef:F,resetCaptions:(0,Z.useCallback)(()=>{g(qe())},[]),stopVideo:(0,Z.useCallback)(()=>{j.current&&=(j.current.stop(),null),O(null),A(`user`),d(!1)},[])}}function xt(e){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Z.useCallback)(t=>{e.setCaptions(e=>nt(e,t)),yt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>ut(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:e.setActiveTool})},[e,o]),waitForGateDecision:(0,Z.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Z.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Z.useCallback)(()=>{a.current?.(new D(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function St(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function Ct(e,t,n,r){r.setCaptions(r=>Qe(r,e,t,n?.interim))}async function wt(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=x({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Tt(e){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Z.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Ke({...e,options:r.options,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{St(e,n.current)},onTranscript:(e,t,r)=>{Ct(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>wt(e,n.current)});return t.current=i,i},[]),clearClient:(0,Z.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Et(e,t,n,r){let[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(!1),d=(0,Z.useCallback)(t=>{u.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Z.useEffect)(()=>{n&&l(e=>e??Date.now())},[n]),(0,Z.useEffect)(()=>{n&&u.current&&(u.current=!1,e.handleToggleVideo())},[e,n]);let f=(0,Z.useCallback)(()=>{u.current=!1,e.teardownSession(),s(!0),l(null)},[e]),[p,m]=(0,Z.useState)([]),h=(0,Z.useCallback)(async()=>{let n=t.current.turns;m(e=>Je(e,n)),s(!1),l(null),await e.handleRestart()},[e,t]),g=(0,Z.useRef)(e.teardownSession);return g.current=e.teardownSession,(0,Z.useEffect)(()=>()=>{g.current()},[]),{callStarted:i,connectedAt:c,ended:o,pastCalls:p,startCall:d,handleEnd:f,handleRestart:h}}function Dt({iface:e,connection:t,...n}){let r=bt(e.labels),i=xt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Z.useRef)(t);a.current=t;let o=I(e.live.ingress,`audio`),s=I(e.live.ingress,`video`),c=I(e.live.ingress,`text`),l=(0,Z.useMemo)(()=>Oe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Z.useMemo)(h,[]),{clientRef:d,ensureClient:f,clearClient:p}=Tt({options:n.options,stated:n.stated,model:n.model,effort:n.effort,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),m=gt({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,connectedAt:_,ended:v,pastCalls:y,startCall:b,handleEnd:x,handleRestart:S}=Et(m,r.captionsRef,r.sessionActive,s),C=JSON.stringify(n.context);(0,Z.useEffect)(()=>{d.current?.setContext(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.options);(0,Z.useEffect)(()=>{d.current?.setOptions(w===void 0?void 0:JSON.parse(w))},[d,w]);let T=JSON.stringify(n.stated);return(0,Z.useEffect)(()=>{d.current?.setStated(T===void 0?void 0:JSON.parse(T))},[d,T]),dt(e.tools.page,n.pageTools),{iface:e,handle:e.identity.handle,traces:u,callStarted:g,connectedAt:_,pastCalls:y,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||v||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:x,startCall:b,handleRestart:S,handleSendText:m.handleSendText,handleToggleMic:m.handleToggleMic,handleFlipCamera:m.handleFlipCamera,handleToggleVideo:m.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=n();function Ot(e){return(0,$.jsx)(R,{children:(0,$.jsx)(kt,{...e})})}function kt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l,showComposer:u=!0,leading:d}){let f=L(),p=f(`@theorem.agent.handle`,{handle:e}),{blocks:m,callStarts:h}=ct(n,t),g=f(`@theorem.live.new_session`),_=Object.fromEntries(h.map(e=>[e,g])),v=u?(0,$.jsx)(ve,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l}):null;return(0,$.jsxs)(V,{height:`100%`,children:[d,(0,$.jsx)(a,{size:`fill`,children:m.length>0?(0,$.jsx)(s,{label:f(`@theorem.panel.captions.name`),children:(0,$.jsx)(fe,{blocks:m,dividers:_,handle:p,streaming:lt(t)})}):(0,$.jsx)(V,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(oe,{icon:(0,$.jsx)(o,{icon:Ee,size:`lg`,color:`secondary`}),title:f(`@theorem.panel.captions.empty.title`),description:f(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),v]})}var At=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new D(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await v(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new D(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new D(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal,execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,background:t.background??a?.background},{vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...P(t,e.profile.labels,F)}),this.close()}}async attach(e,t,n,r,i,a={}){let o=e({send:e=>{typeof e==`string`&&this.receive(JSON.parse(e))},close:()=>this.close(),addEventListener:this.outbound.addEventListener.bind(this.outbound)},t,n,crypto.randomUUID(),r,i,{...a,clientEvents:F});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function jt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new At(e,t,r)}}function Mt({video:e,facingMode:t}){let n=L(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,Z.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(w,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var Nt=720,Pt=320;function Ft({theme:e,mode:t,labels:n,...r}){return(0,$.jsx)(_,{theme:e,mode:t,children:(0,$.jsx)(R,{labels:n,children:(0,$.jsx)(It,{...r})})})}function It({call:e,trace:t,onMinimize:n}){let a=L(),s=(0,Z.useRef)(null),f=pe(e.iface,e.traces,t),p=u(s,!0),m={name:a(`@theorem.panel.captions.name`),show:a(`@theorem.panel.captions.show`),hide:a(`@theorem.panel.captions.hide`),resize:a(`@theorem.panel.captions.resize`)},h=(0,$.jsx)(d,{labels:m,icon:(0,$.jsx)(o,{icon:ge}),panelId:p.id,open:p.open,onToggle:p.toggle});return e.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(c,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,$.jsx)(Ut,{call:e})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(V,{height:`100%`,padding:3,children:(0,$.jsx)(Rt,{call:e,captionsToggle:h,onMinimize:n})})})})})})}),(0,$.jsx)(qt,{prompt:e.gatePrompt,agent:a(`@theorem.agent.handle`,{handle:e.handle}),onResolve:e.resolveGateDecision})]}):(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Lt,{call:e})})})})}function Lt({call:e}){let t=L();return(0,$.jsx)(V,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(b,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:be,gap:8,children:[(0,$.jsxs)(V,{gap:1,children:[(0,$.jsx)(f,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(z,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(p,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(p,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(o,{icon:K}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Rt({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=zt();return(0,$.jsx)(V,{ref:i,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:Nt,height:`100%`,gap:3,children:[(0,$.jsxs)(V,{gap:.5,children:[(0,$.jsx)(f,{type:`label`,color:`secondary`,children:r(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{size:`sm`,color:`secondary`,children:se(r,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(H,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(H,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(a,{size:`fill`,children:(0,$.jsx)(V,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(V,{width:`100%`,height:Pt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(_e,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Bt,{call:e,captionsToggle:t,onMinimize:n})]})})}function zt(){let e=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Bt({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=!e.sessionActive,a=[];return e.voiceAvailable&&a.push((0,$.jsx)(U,{label:r(`@theorem.live.microphone`),tooltip:r(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:i,icon:(0,$.jsx)(o,{icon:te}),pressedIcon:(0,$.jsx)(o,{icon:we}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&a.push((0,$.jsx)(Vt,{call:e},`video`)),n&&a.push((0,$.jsx)(B,{label:r(`@theorem.live.minimize`),tooltip:r(`@theorem.live.minimize`),variant:`ghost`,icon:(0,$.jsx)(o,{icon:Se}),onClick:n},`minimize`)),a.push((0,$.jsx)(Z.Fragment,{children:t},`captions`),(0,$.jsx)(Ht,{call:e},`call`)),(0,$.jsx)(ce,{label:r(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(z,{gap:2,vAlign:`center`,children:a})})}function Vt({call:e}){let t=L(),n=!e.sessionActive;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(U,{label:t(`@theorem.live.camera`),tooltip:t(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:n,icon:(0,$.jsx)(o,{icon:K}),pressedIcon:(0,$.jsx)(o,{icon:De}),onPressedChange:()=>{e.handleToggleVideo()}}),e.isVideoOn?(0,$.jsx)(B,{label:t(`@theorem.live.flip_camera`),tooltip:t(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:n,icon:(0,$.jsx)(o,{icon:Ce}),onClick:()=>{e.handleFlipCamera()}}):null]})}function Ht({call:e}){let t=L();return e.canRestart?(0,$.jsx)(B,{label:t(`@theorem.live.start_call`),tooltip:t(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>{e.handleRestart()}}):(0,$.jsx)(B,{label:t(`@theorem.live.end_call`),tooltip:t(`@theorem.live.end_call`),variant:`destructive`,isDisabled:!e.sessionActive,icon:(0,$.jsx)(o,{icon:Te}),onClick:e.handleEnd})}function Ut({call:e}){return(0,$.jsx)(Ot,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,$.jsx)(Mt,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}var Wt=4,Gt=432,Kt={background:`transparent`,boxShadow:`none`};function qt({prompt:e,agent:t,onResolve:n}){return(0,$.jsx)(le,{isOpen:e!==null,purpose:`required`,width:Gt,padding:Wt,style:Kt,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,$.jsx)(E,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,$.jsx)(T,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function Jt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(Xt,{...t,connect:()=>e?jt(n,e):C(n)})}function Yt({endpoint:e,...t}){let{actingAs:n}=ye();return(0,$.jsx)(Xt,{...t,connect:()=>({createSocket:()=>new WebSocket(xe(e,n))})})}function Xt({payload:e,note:t,connect:n,trace:r,options:i,stated:a,context:o}){let s=(0,Z.useMemo)(()=>g(e),[e]),c=(0,Z.useMemo)(()=>S(e),[e]);return s.type===`live`?(0,$.jsx)(Zt,{iface:s,connection:()=>(t(),n()),trace:r,options:i,stated:a,context:o,pageTools:c}):null}function Zt({trace:e,...t}){let n=Dt(t);return(0,$.jsx)(Ft,{labels:ee,call:n,trace:e})}export{Yt as ProjectLive,Jt as StudioLive};
|
|
5
|
+
`):[])},[r,n])}var ft=.62,pt=400;function mt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function ht(e,t){let n=t?.facingMode??`user`;return mt(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new D(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,ft).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,pt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await mt(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function gt(e){let t=(0,Z.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,Z.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,Z.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>Qe(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,Z.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await ht(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,Z.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,Z.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,Z.useCallback)(async()=>{t(),await n()},[n,t])}}function _t(e,t){return t.activity===void 0&&e?.name===t.name?e:t}function vt(e){return new N(e.kind,e.error,e.message)}function Q(e){e.gateCallId===void 0&&e.clearActiveTool()}function yt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Q(t):e.phase===`error`?(t.reportFailure(vt(e.failure)),Q(t)):t.setActiveTool(e.phase===`running`&&e.activity?{name:e.name,activity:e.activity}:{name:e.name})}function bt(e,t){e.type===`done`?(t.clearInterim(),Q(t)):e.type===`tool`&&yt(e.tool,t)}function xt(e){let[t,n]=(0,Z.useState)(`disconnected`),[r,i]=(0,Z.useState)(null),a=(0,Z.useRef)({input:0,output:0}),o=(0,Z.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,Z.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(!1),[f,p]=(0,Z.useState)(null),[h,g]=(0,Z.useState)(qe),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)(``),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)([]),[ee,te]=(0,Z.useState)(!1),[D,O]=(0,Z.useState)(null),[k,A]=(0,Z.useState)(`user`),j=(0,Z.useRef)(null),M=(0,Z.useRef)(h),N=(0,Z.useRef)(c),P=(0,Z.useRef)(T),F=(0,Z.useRef)(t);return M.current=h,N.current=c,P.current=T,F.current=t,(0,Z.useEffect)(()=>{C&&te(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:f,setActiveTool:p,captions:h,setCaptions:g,failure:_,reportFailure:(0,Z.useCallback)(t=>{v(m(t,e))},[e]),clearFailure:(0,Z.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,Z.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,Z.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:w,sessionPermissions:T,setSessionPermissions:E,everConnected:ee,videoPreview:D,setVideoPreview:O,videoFacingMode:k,setVideoFacingMode:A,videoCaptureRef:j,captionsRef:M,isMutedRef:N,sessionPermissionsRef:P,statusRef:F,resetCaptions:(0,Z.useCallback)(()=>{g(qe())},[]),stopVideo:(0,Z.useCallback)(()=>{j.current&&=(j.current.stop(),null),O(null),A(`user`),d(!1)},[])}}function St(e){let[t,n]=(0,Z.useState)(null),r=(0,Z.useRef)(t);r.current=t;let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),o=(0,Z.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,Z.useCallback)(t=>{e.setCaptions(e=>nt(e,t)),bt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>ut(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:t=>{e.setActiveTool(e=>_t(e,t))}})},[e,o]),waitForGateDecision:(0,Z.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,Z.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,Z.useCallback)(()=>{a.current?.(new D(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function Ct(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function wt(e,t,n,r){r.setCaptions(r=>Qe(r,e,t,n?.interim))}async function Tt(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=x({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Et(e){let t=(0,Z.useRef)(null),n=(0,Z.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,Z.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Ke({...e,options:r.options,stated:r.stated,model:r.model,effort:r.effort,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{Ct(e,n.current)},onTranscript:(e,t,r)=>{wt(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>Tt(e,n.current)});return t.current=i,i},[]),clearClient:(0,Z.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Dt(e,t,n,r){let[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(!1),[c,l]=(0,Z.useState)(null),u=(0,Z.useRef)(!1),d=(0,Z.useCallback)(t=>{u.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,Z.useEffect)(()=>{n&&l(e=>e??Date.now())},[n]),(0,Z.useEffect)(()=>{n&&u.current&&(u.current=!1,e.handleToggleVideo())},[e,n]);let f=(0,Z.useCallback)(()=>{u.current=!1,e.teardownSession(),s(!0),l(null)},[e]),[p,m]=(0,Z.useState)([]),h=(0,Z.useCallback)(async()=>{let n=t.current.turns;m(e=>Je(e,n)),s(!1),l(null),await e.handleRestart()},[e,t]),g=(0,Z.useRef)(e.teardownSession);return g.current=e.teardownSession,(0,Z.useEffect)(()=>()=>{g.current()},[]),{callStarted:i,connectedAt:c,ended:o,pastCalls:p,startCall:d,handleEnd:f,handleRestart:h}}function Ot({iface:e,connection:t,...n}){let r=xt(e.labels),i=St({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,Z.useRef)(t);a.current=t;let o=I(e.live.ingress,`audio`),s=I(e.live.ingress,`video`),c=I(e.live.ingress,`text`),l=(0,Z.useMemo)(()=>Oe({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool?.name??null,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,Z.useMemo)(h,[]),{clientRef:d,ensureClient:f,clearClient:p}=Et({options:n.options,stated:n.stated,model:n.model,effort:n.effort,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),m=gt({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,connectedAt:_,ended:v,pastCalls:y,startCall:b,handleEnd:x,handleRestart:S}=Dt(m,r.captionsRef,r.sessionActive,s),C=JSON.stringify(n.context);(0,Z.useEffect)(()=>{d.current?.setContext(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.options);(0,Z.useEffect)(()=>{d.current?.setOptions(w===void 0?void 0:JSON.parse(w))},[d,w]);let T=JSON.stringify(n.stated);return(0,Z.useEffect)(()=>{d.current?.setStated(T===void 0?void 0:JSON.parse(T))},[d,T]),dt(e.tools.page,n.pageTools),{iface:e,handle:e.identity.handle,traces:u,callStarted:g,connectedAt:_,pastCalls:y,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||v||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:x,startCall:b,handleRestart:S,handleSendText:m.handleSendText,handleToggleMic:m.handleToggleMic,handleFlipCamera:m.handleFlipCamera,handleToggleVideo:m.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var $=n();function kt(e){return(0,$.jsx)(R,{children:(0,$.jsx)(At,{...e})})}function At({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l,showComposer:u=!0,leading:d}){let f=L(),p=f(`@theorem.agent.handle`,{handle:e}),{blocks:m,callStarts:h}=ct(n,t),g=f(`@theorem.live.new_session`),_=Object.fromEntries(h.map(e=>[e,g])),v=u?(0,$.jsx)(ve,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:c,isDisabled:l}):null;return(0,$.jsxs)(V,{height:`100%`,children:[d,(0,$.jsx)(a,{size:`fill`,children:m.length>0?(0,$.jsx)(s,{label:f(`@theorem.panel.captions.name`),children:(0,$.jsx)(fe,{blocks:m,dividers:_,handle:p,streaming:lt(t)})}):(0,$.jsx)(V,{height:`100%`,vAlign:`center`,padding:4,children:(0,$.jsx)(oe,{icon:(0,$.jsx)(o,{icon:Ee,size:`lg`,color:`secondary`}),title:f(`@theorem.panel.captions.empty.title`),description:f(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),v]})}var jt=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new D(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await v(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new D(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new D(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal,execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,background:t.background??a?.background},{vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...P(t,e.profile.labels,F)}),this.close()}}async attach(e,t,n,r,i,a={}){let o=e({send:e=>{typeof e==`string`&&this.receive(JSON.parse(e))},close:()=>this.close(),addEventListener:this.outbound.addEventListener.bind(this.outbound)},t,n,crypto.randomUUID(),r,i,{...a,clientEvents:F});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function Mt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new jt(e,t,r)}}var Nt={borderRadius:`var(--radius-chat, var(--radius-container))`};function Pt({call:e}){let t=L(),n=e.gatePrompt,r=e.resolveGateDecision,i=t(`@theorem.agent.handle`,{handle:e.handle});return(0,$.jsx)(le,{isOpen:n!==null,purpose:`required`,width:400,padding:0,style:Nt,onOpenChange:e=>{e||r({action:`deny`})},children:n?n.gate.kind===`auth`?(0,$.jsx)(E,{gate:n.gate,toolName:n.gate.tool,onAuthenticated:e=>{r({action:`auth`,secret:e})}}):(0,$.jsx)(T,{gate:n.gate,toolName:n.gate.tool,agent:i,input:n.input,onDecision:e=>{r({action:e})}}):null})}function Ft({video:e,facingMode:t}){let n=L(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,Z.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,$.jsx)(w,{ratio:4/3,fit:`cover`,children:(0,$.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var It=720,Lt=320;function Rt({theme:e,mode:t,labels:n,...r}){return(0,$.jsx)(_,{theme:e,mode:t,children:(0,$.jsx)(R,{labels:n,children:(0,$.jsx)(zt,{...r})})})}function zt({call:e,trace:t,onMinimize:n}){let a=L(),s=(0,Z.useRef)(null),f=pe(e.iface,e.traces,t),p=u(s,!0),m={name:a(`@theorem.panel.captions.name`),show:a(`@theorem.panel.captions.show`),hide:a(`@theorem.panel.captions.hide`),resize:a(`@theorem.panel.captions.resize`)},h=(0,$.jsx)(d,{labels:m,icon:(0,$.jsx)(o,{icon:ge}),panelId:p.id,open:p.open,onToggle:p.toggle});return e.callStarted?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(r,{height:`fill`,end:(0,$.jsx)(c,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,$.jsx)(Kt,{call:e})}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(V,{height:`100%`,padding:3,children:(0,$.jsx)(Vt,{call:e,captionsToggle:h,onMinimize:n})})})})})})}),(0,$.jsx)(Pt,{call:e})]}):(0,$.jsx)(W,{inspector:f,children:(0,$.jsx)(r,{ref:s,height:`fill`,header:(0,$.jsx)(l,{children:f.toggle}),content:(0,$.jsx)(i,{padding:0,children:(0,$.jsx)(Bt,{call:e})})})})}function Bt({call:e}){let t=L();return(0,$.jsx)(V,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,$.jsx)(b,{axis:`horizontal`,width:`100%`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:be,gap:8,children:[(0,$.jsxs)(V,{gap:1,children:[(0,$.jsx)(f,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,$.jsxs)(z,{gap:2,wrap:`wrap`,children:[(0,$.jsx)(p,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,$.jsx)(p,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,$.jsx)(o,{icon:K}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Vt({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=Ht();return(0,$.jsx)(V,{ref:i,height:`100%`,hAlign:`center`,children:(0,$.jsxs)(V,{width:`100%`,maxWidth:It,height:`100%`,gap:3,children:[(0,$.jsxs)(V,{gap:.5,children:[(0,$.jsx)(f,{type:`label`,color:`secondary`,children:r(`@theorem.agent.handle`,{handle:e.handle})}),(0,$.jsx)(f,{size:`sm`,color:`secondary`,children:se(r,e.liveState,e.activeTool)})]}),e.failure?(0,$.jsx)(H,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,$.jsx)(H,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,$.jsx)(a,{size:`fill`,children:(0,$.jsx)(V,{height:`100%`,vAlign:`end`,children:(0,$.jsx)(V,{width:`100%`,height:Lt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,$.jsx)(_e,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,$.jsx)(Ut,{call:e,captionsToggle:t,onMinimize:n})]})})}function Ht(){let e=(0,Z.useRef)(null);return(0,Z.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Ut({call:e,captionsToggle:t,onMinimize:n}){let r=L(),i=!e.sessionActive,a=[];return e.voiceAvailable&&a.push((0,$.jsx)(U,{label:r(`@theorem.live.microphone`),tooltip:r(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:i,icon:(0,$.jsx)(o,{icon:te}),pressedIcon:(0,$.jsx)(o,{icon:we}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&a.push((0,$.jsx)(Wt,{call:e},`video`)),n&&a.push((0,$.jsx)(B,{label:r(`@theorem.live.minimize`),tooltip:r(`@theorem.live.minimize`),variant:`ghost`,icon:(0,$.jsx)(o,{icon:Se}),onClick:n},`minimize`)),a.push((0,$.jsx)(Z.Fragment,{children:t},`captions`),(0,$.jsx)(Gt,{call:e},`call`)),(0,$.jsx)(ce,{label:r(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,$.jsx)(z,{gap:2,vAlign:`center`,children:a})})}function Wt({call:e}){let t=L(),n=!e.sessionActive;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(U,{label:t(`@theorem.live.camera`),tooltip:t(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:n,icon:(0,$.jsx)(o,{icon:K}),pressedIcon:(0,$.jsx)(o,{icon:De}),onPressedChange:()=>{e.handleToggleVideo()}}),e.isVideoOn?(0,$.jsx)(B,{label:t(`@theorem.live.flip_camera`),tooltip:t(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:n,icon:(0,$.jsx)(o,{icon:Ce}),onClick:()=>{e.handleFlipCamera()}}):null]})}function Gt({call:e}){let t=L();return e.canRestart?(0,$.jsx)(B,{label:t(`@theorem.live.start_call`),tooltip:t(`@theorem.live.start_call`),variant:`primary`,icon:(0,$.jsx)(o,{icon:G}),onClick:()=>{e.handleRestart()}}):(0,$.jsx)(B,{label:t(`@theorem.live.end_call`),tooltip:t(`@theorem.live.end_call`),variant:`destructive`,isDisabled:!e.sessionActive,icon:(0,$.jsx)(o,{icon:Te}),onClick:e.handleEnd})}function Kt({call:e}){return(0,$.jsx)(kt,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,$.jsx)(Ft,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function qt({runtime:e,...t}){let{payload:n}=t;return(0,$.jsx)(Yt,{...t,connect:()=>e?Mt(n,e):C(n)})}function Jt({endpoint:e,...t}){let{actingAs:n}=ye();return(0,$.jsx)(Yt,{...t,connect:()=>({createSocket:()=>new WebSocket(xe(e,n))})})}function Yt({payload:e,note:t,connect:n,trace:r,options:i,stated:a,context:o}){let s=(0,Z.useMemo)(()=>g(e),[e]),c=(0,Z.useMemo)(()=>S(e),[e]);return s.type===`live`?(0,$.jsx)(Xt,{iface:s,connection:()=>(t(),n()),trace:r,options:i,stated:a,context:o,pageTools:c}):null}function Xt({trace:e,...t}){let n=Ot(t);return(0,$.jsx)(Rt,{labels:ee,call:n,trace:e})}export{Jt as ProjectLive,qt as StudioLive};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cluq4EiW.js";import{a as i}from"./fieldParts-DOfguMAs.js";import{t as a}from"./Text-BDwNaqzZ.js";import{t as o}from"./Button-98PahHB4.js";import{a as s,o as c,t as l}from"./TextInput-BRBEgg_h.js";import{t as u}from"./createReactComponent-DVEyVJ-p.js";import{t as d}from"./ScrollableArea-BGmyGfiL.js";import{a as f,n as p,o as m}from"./type-icons-DgazEJTc.js";import{n as h,t as g}from"./Center-C9ai7fq_.js";import{t as _}from"./IconSearch-BN1R3FIx.js";import{r as v,s as y,t as b}from"./tree-DoI5ABlX.js";import{F as x,i as S}from"./workspace-BpNR3COy.js";import{i as C,n as w,r as T,t as E}from"./map-token-_aDyWhNO.js";import{i as D,n as O,o as k}from"./studio-session-ClF2iNCX.js";import{t as ee}from"./EmptyState-DVoDGbtj.js";import{t as A}from"./IconButton-Jbcy-K-d.js";import{it as j,n as M,tn as N,v as P,xt as F,yt as I}from"./index-D2y4CjDY.js";var L=u(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),R=u(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),z=u(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),B=u(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function V(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function H(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function U(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,S(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,y(e.key)])),a=x(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:S(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:S(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:H(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=S(e,t);return s.has(n)?n:S(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=v(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:S(t.key,b(i.key))});let s=S(t.key,b(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==S(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=y(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[y(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):S(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:F(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=V([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),_=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[_({label:`Providers`,nodes:V([...l.values()],n,g)}),_({label:`Shared settings`,nodes:V(p,n,m)},{label:`Models`,nodes:h}),_({label:`Profiles`,nodes:o}),_({label:`Tools`,nodes:V(f,n,m)})].filter(e=>e.length>0),links:n}}function W(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function G(e){let t=W(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function te(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function ne(e,t){let n=typeof t==`string`?[t]:t,r=G(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=W(e),r=new Map;for(let{link:i,from:a,to:o}of G(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function K(e){return e.kind===`tool`||e.kind===`shared`?2:1}var ae=24,q=8,J=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return G(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function se(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||K(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(oe(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:S,headings:w,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:ee,rails:A}=_(D),j=a/2,M=Math.max(o/2,u),N=[],P=new Map,F=Math.max(a,...y.map(e=>e*J)),I=G(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+j&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+j;return O=Math.max(O,l),[{link:e,from:t,to:n,d:T({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=ee.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(A.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?T(p,m):C(p,m,b,q),S=(e,t)=>t>e.y-M&&t<e.y+e.height+M,w=Math.abs(m.x-p.x)<F+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/ae)).some(t=>t.x>e.x&&t.x<e.x+e.width&&S(e,t.y)));if(w.length===0)return[{link:e,from:t,to:n,d:x.d}];let[I,L]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],R=e=>{let t=[...w];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-M:Math.max(...t.map(e=>e.y+e.height))+M,r=[...s,...N].filter(e=>!t.includes(e)&&e.x<L&&e.x+e.width>I&&S(e,n));if(r.length===0)return n;t.push(...r)}},z=e=>Math.abs(i.y-e)+Math.abs(o.y-e),B=`${f}:${y}`,V=P.get(B)??(()=>{let[e,t]=[R(-1),R(1)],n=e>=0&&z(e)<=z(t)?e:t;return N.push({id:``,x:I,y:n-q+M,width:L-I,height:2*(q-M)}),P.set(B,n),n})();k=Math.max(k,V);let H=d?p.x+l*J:b,U=d?b:m.x-l*J,W={x:(H+U)/2,y:V};return[{link:e,from:t,to:n,d:C(p,W,H,q).d+C(W,m,U,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:S,headings:w,lines:I}}var Y=e(t(),1),ce={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${O}.map`:`${O}.map.project:${e}`;function le(e){if(!D(e))return{};let t={};for(let[n,r]of Object.entries(e))D(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function ue(e){try{let t=JSON.parse(k()?.getItem(X(e))??`null`);return D(t)?{tokens:le(t.tokens),detail:le(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:ce}catch{return ce}}function de(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?k()?.removeItem(X(e)):k()?.setItem(X(e),JSON.stringify(t))}function fe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function pe(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var me=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function he(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=me(e.left,a.scrollWidth-a.clientWidth),r=me(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var ge=e=>e.button===0&&e.pointerType!==`touch`;function _e(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ve(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!ge(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),_e(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),ye={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},be={...ye,node:{width:240,height:84}},xe=28;function Se(e){return e.length>xe?`${e.slice(0,27)}…`:e}function Ce({kind:e,type:t,note:n}){return(e===`agent`?f(t):void 0)||(e===`tool`?m(t??``):e===`model`?P(n)??M.modelBinding:e===`provider`?N:e===`shared`&&t&&Object.hasOwn(M,t)?M[t]:e===`agent`?p.text:c)}function we(e){return Object.hasOwn(M,e)?M[e]:c}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Te=4,Ee=24,De={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function Oe(e){let t=I()?.name,[n,r]=(0,Y.useState)(()=>ue(t)),i=e=>{r(e),de(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:ne(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function ke(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!ge(o))return;let c;_e(o,(e,r)=>{!c&&Math.hypot(e,r)<Te||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?De[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Ee,0),c=Math.max(o.y+a.y*Ee,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function Ae(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{let n=new Set,r=new Set;if(t===void 0)return[n,r];n.add(t);for(let{link:i,from:a,to:o}of e.lines)if([i.from,i.to,a,o].includes(t)){r.add(i);for(let e of[i.from,i.to,a,o])n.add(e)}return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function je(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return he(n,e=>{let{left:t,top:r}=pe(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Me(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:c,tidy:l}=n,u=[];e&&e.id!==r&&u.push({label:`Show only its family`,icon:z,onClick:()=>{o(e.id)}});let d=e?.opens;d!==void 0&&u.push({label:`Open`,icon:h,onClick:()=>{t(d)}}),e&&u.push({type:`divider`});let f={label:`Show everything`,icon:s,onClick:()=>{o(void 0)}};return[...u,...r===void 0?[]:[f],{label:i?`Collapse`:`Expand`,icon:i?R:L,onClick:c},{label:`Tidy`,icon:B,isDisabled:!a,onClick:l}]}function Ne({actions:e,query:t,onQuery:n,onClose:a}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:p,tidy:m}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(l,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:_,hasClear:!0,value:t,onChange:n}),c!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:s,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:B,size:`sm`}),onClick:m}),(0,Z.jsx)(A,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:u?R:L,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:p}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Pe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(E,{id:t.id,label:Se(t.long??t.label),icon:Ce(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>xe?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:Ce(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:K(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:we(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Ie({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:c,map:l,moved:u,put:f,showFamily:p,expand:m}=Oe((0,Y.useMemo)(()=>U(e,t),[e,t])),[h,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>te(l,h),[l,h]),b=(0,Y.useMemo)(()=>h.trim()===``?l:ne(l,y),[l,h,y]),x=h.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),C=s?be:ye,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=w(S,T),D=(0,Y.useMemo)(()=>se(b,C,{moved:u,widths:E,detail:s}),[b,C,s,u,E]),O=b.columns.flat().flatMap(e=>e.nodes),k=O.find(e=>Q(e,n))?.id;je(S,c,{place:k===void 0?void 0:D.nodes[k],sizes:C});let{dragging:A,draggable:M}=ke(D,u,f),{panning:N,pan:P}=ve(`[data-map-node]`),{lit:F,on:I,onLines:L,lights:R}=Ae(D),z={family:c,expanded:s,isMoved:O.some(e=>Object.hasOwn(u,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[B,V]=(0,Y.useState)(),H=Me(O.find(e=>e.id===B),i,z),W=s?Fe:Pe,G=e=>L.has(e.link)?2:+(e.from===k||e.to===k),re=[...D.lines].sort((e,t)=>G(e)-G(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&c!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(d,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(j,{items:H,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":F===void 0||A!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:P,onContextMenuCapture:e=>{V(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(C.node.width)}px`,"--map-line":`${String(C.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:re.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":L.has(e)?``:void 0,"data-open":t===k||n===k?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(W,{node:e,place:t,joins:ie(b,e.id),selected:n,on:I,isFound:y.includes(e.id),isDragging:A===e.id,onOpen:i,lights:R,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(g,{className:`studio-map-nothing`,children:(0,Z.jsx)(ee,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:_,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Ne,{actions:z,query:h,onQuery:v,onClose:o})]})}export{Ie as StudioMap};
|
|
1
|
+
import{r as e}from"./rolldown-runtime-hePW80VL.js";import{d as t,l as n}from"./themeProps-Bo2jNkIC.js";import{t as r}from"./Icon-Cluq4EiW.js";import{a as i}from"./fieldParts-DOfguMAs.js";import{t as a}from"./Text-BDwNaqzZ.js";import{t as o}from"./Button-98PahHB4.js";import{a as s,o as c,t as l}from"./TextInput-BRBEgg_h.js";import{t as u}from"./createReactComponent-DVEyVJ-p.js";import{t as d}from"./ScrollableArea-BGmyGfiL.js";import{a as f,n as p,o as m}from"./type-icons-DgazEJTc.js";import{n as h,t as g}from"./Center-C9ai7fq_.js";import{t as _}from"./IconSearch-BN1R3FIx.js";import{r as v,s as y,t as b}from"./tree-DoI5ABlX.js";import{F as x,i as S}from"./workspace-BpNR3COy.js";import{i as C,n as w,r as T,t as E}from"./map-token-_aDyWhNO.js";import{i as D,n as O,o as k}from"./studio-session-ClF2iNCX.js";import{t as ee}from"./EmptyState-DVoDGbtj.js";import{t as A}from"./IconButton-Jbcy-K-d.js";import{it as j,n as M,tn as N,v as P,xt as F,yt as I}from"./index-CiwarrRR.js";var L=u(`outline`,`arrows-maximize`,`ArrowsMaximize`,[[`path`,{d:`M16 4l4 0l0 4`,key:`svg-0`}],[`path`,{d:`M14 10l6 -6`,key:`svg-1`}],[`path`,{d:`M8 20l-4 0l0 -4`,key:`svg-2`}],[`path`,{d:`M4 20l6 -6`,key:`svg-3`}],[`path`,{d:`M16 20l4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M14 14l6 6`,key:`svg-5`}],[`path`,{d:`M8 4l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M4 4l6 6`,key:`svg-7`}]]),R=u(`outline`,`arrows-minimize`,`ArrowsMinimize`,[[`path`,{d:`M5 9l4 0l0 -4`,key:`svg-0`}],[`path`,{d:`M3 3l6 6`,key:`svg-1`}],[`path`,{d:`M5 15l4 0l0 4`,key:`svg-2`}],[`path`,{d:`M3 21l6 -6`,key:`svg-3`}],[`path`,{d:`M19 9l-4 0l0 -4`,key:`svg-4`}],[`path`,{d:`M15 9l6 -6`,key:`svg-5`}],[`path`,{d:`M19 15l-4 0l0 4`,key:`svg-6`}],[`path`,{d:`M15 15l6 6`,key:`svg-7`}]]),z=u(`outline`,`focus-2`,`Focus2`,[[`path`,{d:`M11.5 12a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0`,fill:`currentColor`,key:`svg-0`}],[`path`,{d:`M5 12a7 7 0 1 0 14 0a7 7 0 1 0 -14 0`,key:`svg-1`}],[`path`,{d:`M12 3l0 2`,key:`svg-2`}],[`path`,{d:`M3 12l2 0`,key:`svg-3`}],[`path`,{d:`M12 19l0 2`,key:`svg-4`}],[`path`,{d:`M19 12l2 0`,key:`svg-5`}]]),B=u(`outline`,`layout-grid`,`LayoutGrid`,[[`path`,{d:`M4 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-0`}],[`path`,{d:`M14 5a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-1`}],[`path`,{d:`M4 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-2`}],[`path`,{d:`M14 15a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1l0 -4`,key:`svg-3`}]]);function V(e,t,n){let r=e=>{let r=t.flatMap(({from:t,to:n})=>t===e.id?[n]:n===e.id?[t]:[]).flatMap(e=>n.get(e)??[]);return r.length===0?1/0:r.reduce((e,t)=>e+t,0)/r.length},i=new Map(e.map(e=>[e.id,r(e)])),a=e=>i.get(e.id)??1/0;return[...e].sort((e,t)=>a(e)===a(t)?0:a(e)-a(t))}function H(e,t,n){return t===`models`?e.modelBindings.map(e=>e.modelId.trim()||`Unnamed model`).join(`, `):t===`tools`?String(e.tools.allow.filter(e=>n.has(e)).length):t===`outputs`?e.outputs.mode:``}function U(e,t=[]){let n=[],r=new Map(e.agents.map(e=>[e.key,S(e.key)])),i=new Map(e.toolSpecs.map(e=>[e.key,y(e.key)])),a=x(e),o=e.agents.map((e,t)=>{let{agentId:n,profileType:r,handle:o}=e.identity,s=r||`text`;return{id:S(e.key),kind:`agent`,label:n.trim()||`Unnamed agent`,note:o?`${s} · ${o}`:s,opens:S(e.key),type:s,rows:(a.agents[t]?.children??[]).map(t=>({id:t.id,label:t.label,note:H(e,t.ref.facet,i),opens:t.id,type:t.ref.facet}))}}),s=new Set(o.flatMap(e=>e.rows??[]).map(e=>e.id)),c=(e,t)=>{let n=S(e,t);return s.has(n)?n:S(e)},l=new Map,u=new Map(e.providers.map(e=>[e.id,e.definition])),d=new Map;for(let t of e.agents){let e=c(t.key,`models`);for(let i of t.modelBindings){let a=`model:${i.provider}:${i.apiId}:${i.modelId}`,o=v(i.provider);l.has(o)||l.set(o,{id:o,kind:`provider`,label:i.provider,note:``,opens:u.has(i.provider)?o:S(t.key,b(i.key))});let s=S(t.key,b(i.key)),c=d.get(a);c?c.holds?.push(s):(d.set(a,{id:a,kind:`model`,label:i.modelId.trim()||`Unnamed model`,note:i.apiId,opens:s,holds:[s]}),n.push({from:o,to:a,kind:`serves`})),n.some(t=>t.from===a&&t.to===e)||n.push({from:a,to:e,kind:`runs`});let f=i.compactWith?r.get(i.compactWith):void 0,p=n.some(t=>t.kind===`summarised`&&t.from===e);f&&f!==S(t.key)&&!p&&n.push({from:e,to:f,kind:`summarised`})}for(let e of t.tools.allow){let r=i.get(e);r&&n.push({from:c(t.key,`tools`),to:r,kind:`allows`})}}let f=e.toolSpecs.map(e=>{let t=y(e.key),i=e.toolType===`agent`?r.get(e.agentKey??``):r.get(e.stageAgentKey??``);return i&&n.push({from:t,to:i,kind:`asks`}),{id:t,kind:`tool`,label:e.toolName.trim()||`Unnamed tool`,note:e.description,opens:t,type:e.toolType}}),p=t.map(t=>{let{setting:i,facet:a}=t,o=`shared:${i.file}:${i.name}`,s=t.agents.filter(e=>r.has(e)),l=i.tools.flatMap(t=>{let n=e.toolSpecs.find(e=>e.toolName===t);return n?[y(n.key)]:[]});for(let e of s)n.push({from:o,to:a?c(e,a):S(e),kind:`sets`});for(let e of l)n.push({from:o,to:e,kind:`sets`});return{id:o,kind:`shared`,label:i.label,note:`${i.name} · ${i.file}:${String(i.line)}`,opens:F(t)??l[0],type:a}}),m=new Map(o.flatMap((e,t)=>[e.id,...(e.rows??[]).map(e=>e.id)].map(e=>[e,t])));for(let e of d.values())[...d.values()].some(t=>t!==e&&t.label===e.label)&&e.note&&(e.long=`${e.label} · ${e.note}`);let h=V([...d.values()],n,m),g=new Map(h.map((e,t)=>[e.id,t])),_=(...e)=>e.filter(e=>e.nodes.length>0);return{columns:[_({label:`Providers`,nodes:V([...l.values()],n,g)}),_({label:`Shared settings`,nodes:V(p,n,m)},{label:`Models`,nodes:h}),_({label:`Profiles`,nodes:o}),_({label:`Tools`,nodes:V(f,n,m)})].filter(e=>e.length>0),links:n}}function W(e){let t=e.columns.flat().flatMap(e=>e.nodes);return new Map(t.flatMap(e=>[e.id,...(e.rows??[]).map(e=>e.id)].map(t=>[t,e])))}function G(e){let t=W(e);return e.links.flatMap(e=>{let n=t.get(e.from)?.id,r=t.get(e.to)?.id;return n!==void 0&&r!==void 0?[{link:e,from:n,to:r}]:[]})}function te(e,t){let n=t.trim().toLowerCase();return n===``?[]:e.columns.flat().flatMap(e=>e.nodes).filter(e=>[e.label,e.long??``,e.note].some(e=>e.toLowerCase().includes(n))).map(e=>e.id)}function ne(e,t){let n=typeof t==`string`?[t]:t,r=G(e),i=(e,t)=>{let i=new Set(n),a=[...n];for(let n=a.pop();n!==void 0;n=a.pop())for(let o of r)o[e]!==n||i.has(o[t])||(i.add(o[t]),a.push(o[t]));return i},a=new Set([...i(`to`,`from`),...i(`from`,`to`)]),o=e.columns.map(e=>e.map(e=>({...e,nodes:e.nodes.filter(e=>a.has(e.id))})).filter(e=>e.nodes.length>0)).filter(e=>e.length>0),s=new Set(r.filter(({from:e,to:t})=>a.has(e)&&a.has(t)).map(({link:e})=>e));return{columns:o,links:e.links.filter(e=>s.has(e))}}var re={serves:[`Serves`,`Served by`],sets:[`Sets`,`Set by`],runs:[`Runs`,`Runs on`],allows:[`Allows`,`Allowed by`],asks:[`Asks`,`Asked by`],summarised:[`Summarised by`,`Summarises for`]};function ie(e,t){let n=W(e),r=new Map;for(let{link:i,from:a,to:o}of G(e)){if(a!==t&&o!==t)continue;let e=re[i.kind][a===t?0:1],s=n.get(a===t?o:a)?.label;s!==void 0&&r.set(e,[...r.get(e)??[],s])}return[...r].map(([e,t])=>`${e} ${t.join(`, `)}.`).join(` `)}function K(e){return e.kind===`tool`||e.kind===`shared`?2:1}var ae=24,q=8,J=16;function oe(e,t,n){let r=new Map,i=(e,t)=>`${e}:${String(t)}`;return G(e).flatMap(({link:e})=>{let[a,o]=[t(e.from),t(e.to)];if(a===void 0||o===void 0||Math.abs(a-o)<n)return[];let s=a<o?1:-1;for(let t of[i(e.from,s),i(e.to,-s)])r.set(t,(r.get(t)??0)+1);return[{link:e,way:s}]}).map(({link:e,way:t})=>{let[n,a]=[i(e.from,t),i(e.to,-t)],o=(r.get(n)??0)>=(r.get(a)??0);return{link:e,way:t,leaves:o,hub:o?n:a}})}function se(e,t,n={}){let{node:r,card:i,columnGap:a,rowGap:o,heading:s,groupGap:c,padding:l,lineGap:u}=t,{moved:d={},widths:f={},detail:p=!1}=n,m=new Map;e.columns.forEach((e,t)=>{for(let n of e)for(let e of n.nodes)if(!Object.hasOwn(d,e.id))for(let n of[e.id,...(e.rows??[]).map(e=>e.id)])m.set(n,t)});let h=t=>{let n={},a=[],u=[],m=new Map,h=0,g=0;return e.columns.forEach((e,_)=>{let v=t[_]??l,y=l;e.forEach((e,t)=>{t>0&&(y+=c),a.push({label:e.label,x:v,y}),u.push({id:`heading:${_}:${t}`,x:v,y,width:r.width,height:s}),y+=s;for(let t of e.nodes){let e=p?t.rows??[]:[],a=e.length>0||t.note!==``,s=p&&(e.length>0||K(t)===1)?i.head:r.height,c=p&&!a?i.row:s,l=e.length>0?i.head+e.length*i.row+i.foot:c,_=Math.min(f[t.id]??r.width,r.width),b=Object.hasOwn(d,t.id)?d[t.id]:void 0,x=b?{x:Math.max(b.x,0),y:Math.max(b.y,0)}:{x:v,y};n[t.id]={...x,height:l},u.push({id:t.id,...x,width:_,height:l});let S={left:x.x,right:x.x+_,y:x.y+(p?i.row:c)/2};m.set(t.id,S);for(let[e,n]of(t.rows??[]).entries())m.set(n.id,p?{...S,y:x.y+i.head+e*i.row+i.row/2}:S);h=Math.max(h,x.x+r.width),g=Math.max(g,x.y+l),y+=l+o}y-=o})}),{nodes:n,headings:a,boxes:u,ports:m,right:h,bottom:g}},g=(e,t,n)=>{let{way:i,leaves:a}=e,o={x:i>0?t.right+u:t.left-u,y:t.y},s={x:i>0?n.left-u:n.right+u,y:n.y},c=i>0?Math.max(t.left+r.width,t.right)+u:o.x,l=i>0?s.x:Math.max(n.left+r.width,n.right)+u,d=a?l:c,f=a?-i:i;return{start:o,end:s,side:d,into:f,room:Math.abs(l-c),strip:`${String(d)}:${String(f)}`}},_=t=>{let n=new Map(oe(e,e=>t.get(e)?.left,r.width).map(e=>[e.link,e])),i=new Map;for(let e of n.values()){let n=t.get(e.link.from),r=t.get(e.link.to);if(!n||!r||n.y===r.y)continue;let{strip:a}=g(e,n,r),o=i.get(a)??new Map,s=e.leaves?e.link.to:e.link.from,c=o.get(e.hub)??{y:e.leaves?n.y:r.y,joins:[],beside:s};c.joins.push(e.leaves?r.y:n.y),i.set(a,o.set(e.hub,c))}let a=new Map,o=new Map;for(let[e,t]of i){let n=e=>e.reduce((e,t)=>e+t,0)/e.length,r=[...t.values()],i=n(r.flatMap(e=>e.joins))>=n(r.map(e=>e.y)),s=[];for(let[n,r]of[...t].sort(([,e],[,t])=>i?e.y-t.y:t.y-e.y)){let t=Math.min(r.y,...r.joins)-q,i=Math.max(r.y,...r.joins)+q,o=s.findIndex(e=>e.every(e=>i<e.low||t>e.high)),c=o<0?s.length:o;s[c]=[...s[c]??[],{low:t,high:i}],a.set(`${e}:${n}`,c)}let[c]=r;c&&o.set(e,{count:s.length,beside:c.beside,into:Number(e.split(`:`)[1])})}return{spans:n,rails:a,held:o}},v=e.columns.map((e,t)=>l+t*(r.width+a)),y=e.columns.map(()=>0);for(let{count:e,beside:t,into:n}of _(h(v).ports).held.values()){let r=m.get(t);if(r===void 0)continue;let i=n>0?r:r-1;i>=0&&i<y.length&&(y[i]=(y[i]??0)+e+1)}let b=[l];for(let[e,t]of y.entries())b.push((b[e]??l)+r.width+Math.max(a,t*J));let x=h(b),{nodes:S,headings:w,boxes:E,ports:D}=x,{right:O,bottom:k}=x,{spans:ee,rails:A}=_(D),j=a/2,M=Math.max(o/2,u),N=[],P=new Map,F=Math.max(a,...y.map(e=>e*J)),I=G(e).flatMap(({link:e,from:t,to:n})=>{let i=D.get(e.from),o=D.get(e.to);if(!i||!o)return[];let s=E.filter(e=>e.id!==t&&e.id!==n);if(Math.abs(i.left-o.left)<r.width){let r=i.right+u,a=o.right+u,c=s.filter(e=>e.y<Math.max(i.y,o.y)&&e.y+e.height>Math.min(i.y,o.y)&&e.x<Math.max(r,a)+j&&e.x+e.width>Math.min(i.left,o.left)),l=Math.max(r,a,...c.map(e=>e.x+e.width))+j;return O=Math.max(O,l),[{link:e,from:t,to:n,d:T({x:r,y:i.y},{x:a,y:o.y},l).d}]}let c=ee.get(e);if(!c)return[];let{way:l,leaves:d,hub:f}=c,{start:p,end:m,side:h,into:_,room:v,strip:y}=g(c,i,o),b=h+_*Math.min((1+(A.get(`${y}:${f}`)??0))*J,Math.max(v-J,0)),x=v<32?T(p,m):C(p,m,b,q),S=(e,t)=>t>e.y-M&&t<e.y+e.height+M,w=Math.abs(m.x-p.x)<F+a?[]:s.filter(e=>Array.from({length:23},(e,t)=>x.at((t+1)/ae)).some(t=>t.x>e.x&&t.x<e.x+e.width&&S(e,t.y)));if(w.length===0)return[{link:e,from:t,to:n,d:x.d}];let[I,L]=[Math.min(p.x,m.x),Math.max(p.x,m.x)],R=e=>{let t=[...w];for(;;){let n=e<0?Math.min(...t.map(e=>e.y))-M:Math.max(...t.map(e=>e.y+e.height))+M,r=[...s,...N].filter(e=>!t.includes(e)&&e.x<L&&e.x+e.width>I&&S(e,n));if(r.length===0)return n;t.push(...r)}},z=e=>Math.abs(i.y-e)+Math.abs(o.y-e),B=`${f}:${y}`,V=P.get(B)??(()=>{let[e,t]=[R(-1),R(1)],n=e>=0&&z(e)<=z(t)?e:t;return N.push({id:``,x:I,y:n-q+M,width:L-I,height:2*(q-M)}),P.set(B,n),n})();k=Math.max(k,V);let H=d?p.x+l*J:b,U=d?b:m.x-l*J,W={x:(H+U)/2,y:V};return[{link:e,from:t,to:n,d:C(p,W,H,q).d+C(W,m,U,q).d.replace(/^M \S+ \S+/,``)}]});return{width:Math.max((b[Math.max(e.columns.length-1,0)]??l)+r.width,O)+l,height:Math.max(k,l)+l,nodes:S,headings:w,lines:I}}var Y=e(t(),1),ce={tokens:{},detail:{},expanded:!1},X=e=>e===void 0?`${O}.map`:`${O}.map.project:${e}`;function le(e){if(!D(e))return{};let t={};for(let[n,r]of Object.entries(e))D(r)&&typeof r.x==`number`&&typeof r.y==`number`&&(t[n]={x:r.x,y:r.y});return t}function ue(e){try{let t=JSON.parse(k()?.getItem(X(e))??`null`);return D(t)?{tokens:le(t.tokens),detail:le(t.detail),expanded:t.expanded===!0,...typeof t.family==`string`?{family:t.family}:{}}:ce}catch{return ce}}function de(e,t){let{tokens:n,detail:r,expanded:i,family:a}=t;Object.keys(n).length===0&&Object.keys(r).length===0&&!i&&a===void 0?k()?.removeItem(X(e)):k()?.setItem(X(e),JSON.stringify(t))}function fe(e){for(let t=e.parentElement;t;t=t.parentElement){let{overflowX:e,overflowY:n}=getComputedStyle(t);if(/auto|scroll/.test(`${e} ${n}`))return t}}function pe(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return{left:n.left-r.left+t.scrollLeft,top:n.top-r.top+t.scrollTop}}var me=(e,t)=>Math.min(Math.max(e,0),Math.max(t,0));function he(e,t){let n=0,r=120,i=()=>{--r;let a=fe(e);if(a&&a.scrollWidth>a.clientWidth){let e=t(a),n=me(e.left,a.scrollWidth-a.clientWidth),r=me(e.top,a.scrollHeight-a.clientHeight);if(a.scrollTo({left:n,top:r,behavior:`instant`}),Math.abs(a.scrollLeft-n)<1&&Math.abs(a.scrollTop-r)<1)return}r>0&&(n=requestAnimationFrame(i))};return i(),()=>{cancelAnimationFrame(n)}}var ge=e=>e.button===0&&e.pointerType!==`touch`;function _e(e,t,n){let{pointerId:r,clientX:i,clientY:a}=e,o=e=>{e.pointerId===r&&t(e.clientX-i,e.clientY-a)},s=e=>{e.pointerId===r&&(globalThis.removeEventListener(`pointermove`,o),globalThis.removeEventListener(`pointerup`,s),globalThis.removeEventListener(`pointercancel`,s),n(e.type===`pointerup`))};globalThis.addEventListener(`pointermove`,o),globalThis.addEventListener(`pointerup`,s),globalThis.addEventListener(`pointercancel`,s)}function ve(e){let[t,n]=(0,Y.useState)(!1);return{panning:t,pan:t=>{if(!ge(t)||t.target.closest(e))return;let r=fe(t.currentTarget);if(!r)return;let{scrollLeft:i,scrollTop:a}=r;n(!0),_e(t,(e,t)=>{r.scrollTo({left:i-e,top:a-t,behavior:`instant`})},()=>{n(!1)})}}}var Z=n(),ye={node:{width:240,height:24},card:{head:60,row:28,foot:4},columnGap:96,rowGap:6,heading:24,groupGap:16,padding:24,lineGap:8},be={...ye,node:{width:240,height:84}},xe=28;function Se(e){return e.length>xe?`${e.slice(0,27)}…`:e}function Ce({kind:e,type:t,note:n}){return(e===`agent`?f(t):void 0)||(e===`tool`?m(t??``):e===`model`?P(n)??M.modelBinding:e===`provider`?N:e===`shared`&&t&&Object.hasOwn(M,t)?M[t]:e===`agent`?p.text:c)}function we(e){return Object.hasOwn(M,e)?M[e]:c}function Q(e,t){return e.kind===`agent`?t===e.id||t.startsWith(`${e.id}/`):e.kind===`model`?e.holds?.includes(t)??!1:e.kind===`tool`&&t===e.id}var Te=4,Ee=24,De={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}};function Oe(e){let t=I()?.name,[n,r]=(0,Y.useState)(()=>ue(t)),i=e=>{r(e),de(t,e)},{expanded:a}=n,o=e.columns.flat().some(e=>e.nodes.some(e=>e.id===n.family))?n.family:void 0,s=(0,Y.useMemo)(()=>o===void 0?e:ne(e,o),[e,o]),[c,l]=(0,Y.useState)({}),u=a?`detail`:`tokens`;return{expanded:a,family:o,map:s,moved:o===void 0?n[u]:c,put(e,t){o===void 0?t?i({...n,[u]:e}):r({...n,[u]:e}):l(e)},showFamily(e){l({});let{tokens:t,detail:r}=n;i({tokens:t,detail:r,expanded:a,...e===void 0?{}:{family:e}})},expand(){i({...n,expanded:!a})}}}function ke(e,t,n){let r=(0,Y.useRef)(!1),[i,a]=(0,Y.useState)();return{dragging:i,draggable:i=>({onPointerDown:o=>{r.current=!1;let s=e.nodes[i];if(!s||!ge(o))return;let c;_e(o,(e,r)=>{!c&&Math.hypot(e,r)<Te||(c||a(i),c={...t,[i]:{x:Math.max(s.x+e,0),y:Math.max(s.y+r,0)}},n(c,!1))},e=>{c&&(r.current=e,globalThis.setTimeout(()=>{r.current=!1},0),a(void 0),n(c,!0))})},onClickCapture:e=>{r.current&&(r.current=!1,e.stopPropagation(),e.preventDefault())},onKeyDown:r=>{let a=r.altKey?De[r.key]:void 0,o=e.nodes[i];if(!a||!o)return;r.preventDefault();let s=Math.max(o.x+a.x*Ee,0),c=Math.max(o.y+a.y*Ee,0);n({...t,[i]:{x:s,y:c}},!0)}})}}function Ae(e){let[t,n]=(0,Y.useState)(),[r,i]=(0,Y.useMemo)(()=>{let n=new Set,r=new Set;if(t===void 0)return[n,r];n.add(t);for(let{link:i,from:a,to:o}of e.lines)if([i.from,i.to,a,o].includes(t)){r.add(i);for(let e of[i.from,i.to,a,o])n.add(e)}return[n,r]},[e,t]);return{lit:t,on:r,onLines:i,lights:e=>({onPointerEnter:()=>{n(e)},onPointerLeave:()=>{n(void 0)},onFocus:()=>{n(e)},onBlur:()=>{n(void 0)}})}}function je(e,t,n){let r=(0,Y.useRef)(n.place);r.current=n.place;let{sizes:i}=n;(0,Y.useEffect)(()=>{let n=e.current;if(!n)return;let a=r.current,o=t===void 0?a:void 0;return he(n,e=>{let{left:t,top:r}=pe(n,e);return o===void 0?{left:t,top:r}:{left:t+o.x+i.node.width/2-e.clientWidth/2,top:r+o.y+o.height/2-e.clientHeight/2}})},[e,t,i])}function Me(e,t,n){let{family:r,expanded:i,isMoved:a,showFamily:o,expand:c,tidy:l}=n,u=[];e&&e.id!==r&&u.push({label:`Show only its family`,icon:z,onClick:()=>{o(e.id)}});let d=e?.opens;d!==void 0&&u.push({label:`Open`,icon:h,onClick:()=>{t(d)}}),e&&u.push({type:`divider`});let f={label:`Show everything`,icon:s,onClick:()=>{o(void 0)}};return[...u,...r===void 0?[]:[f],{label:i?`Collapse`:`Expand`,icon:i?R:L,onClick:c},{label:`Tidy`,icon:B,isDisabled:!a,onClick:l}]}function Ne({actions:e,query:t,onQuery:n,onClose:a}){let{family:c,expanded:u,isMoved:d,showFamily:f,expand:p,tidy:m}=e;return(0,Z.jsxs)(`div`,{className:`studio-map-tools`,children:[(0,Z.jsx)(l,{label:`Search the map`,isLabelHidden:!0,size:`sm`,width:200,placeholder:`Search`,startIcon:_,hasClear:!0,value:t,onChange:n}),c!==void 0&&(0,Z.jsx)(o,{label:`Show everything`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:s,size:`sm`}),onClick:()=>{f(void 0)}}),d&&(0,Z.jsx)(o,{label:`Tidy`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:B,size:`sm`}),onClick:m}),(0,Z.jsx)(A,{label:u?`Collapse`:`Expand`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:u?R:L,size:`sm`}),tooltip:u?`Show each node as a token`:`Show sections and descriptions`,onClick:p}),(0,Z.jsx)(A,{label:`Close map`,variant:`ghost`,size:`sm`,icon:(0,Z.jsx)(r,{icon:i,size:`sm`}),tooltip:`Close the map`,onClick:a})]})}function $({node:e,on:t,isFound:n,isDragging:r}){let i=t.has(e.id)||(e.rows??[]).some(e=>t.has(e.id));return{"data-map-node":e.id,"data-on":i?``:void 0,"data-found":n?``:void 0,"data-dragging":r?``:void 0}}function Pe(e){let{node:t,place:n,joins:r,selected:i,onOpen:a,lights:o,drag:s}=e,{opens:c}=t,l=Q(t,i);return(0,Z.jsx)(E,{id:t.id,label:Se(t.long??t.label),icon:Ce(t),x:n.x,y:n.y+n.height/2,color:l?`blue`:void 0,description:[t.note,r].filter(Boolean).join(`. `)||void 0,onOpen:c===void 0?void 0:()=>{a(c)},title:(t.long??t.label).length>xe?t.long??t.label:void 0,"aria-current":l?`true`:void 0,...$(e),...o(t.id),...s})}function Fe(e){let{node:t,place:n,joins:i,selected:o,on:s,onOpen:c,lights:l,drag:u}=e,{opens:d}=t,f=t.rows??[],p={left:n.x,top:n.y,height:n.height},m=(0,Z.jsxs)(Z.Fragment,{children:[(0,Z.jsxs)(`span`,{className:`studio-map-name`,children:[(0,Z.jsx)(r,{icon:Ce(t),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:t.label})]}),t.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:f.length>0?1:K(t),hasTruncateTooltip:!1,className:`studio-map-note`,children:t.note})]}),h={type:`button`,title:t.note||void 0,"aria-description":i||void 0,disabled:d===void 0,onClick:()=>{d!==void 0&&c(d)},...l(t.id)};return f.length===0?(0,Z.jsx)(`button`,{...h,...u,...$(e),className:`studio-map-node`,"data-map-token":t.id,style:p,"aria-current":Q(t,o)?`true`:void 0,children:m}):(0,Z.jsxs)(`div`,{className:`studio-map-card`,"data-map-token":t.id,style:p,"data-open":Q(t,o)?``:void 0,...$(e),...u,children:[(0,Z.jsx)(`button`,{...h,className:`studio-map-head`,"aria-current":o===t.id?`true`:void 0,children:m}),f.map(e=>(0,Z.jsxs)(`button`,{type:`button`,className:`studio-map-row`,"aria-current":o===e.id?`true`:void 0,"data-on":s.has(e.id)?``:void 0,onClick:()=>{c(e.opens)},...l(e.id),children:[(0,Z.jsx)(r,{icon:we(e.type),size:`sm`}),(0,Z.jsx)(a,{type:`supporting`,color:`inherit`,weight:`medium`,maxLines:1,hasTruncateTooltip:!1,children:e.label}),e.note&&(0,Z.jsx)(a,{type:`supporting`,maxLines:1,justify:`end`,hasTruncateTooltip:!1,className:`studio-map-row-note`,children:e.note})]},e.id))]})}function Ie({workspace:e,shared:t,selected:n,onOpen:i,onClose:o}){let{expanded:s,family:c,map:l,moved:u,put:f,showFamily:p,expand:m}=Oe((0,Y.useMemo)(()=>U(e,t),[e,t])),[h,v]=(0,Y.useState)(``),y=(0,Y.useMemo)(()=>te(l,h),[l,h]),b=(0,Y.useMemo)(()=>h.trim()===``?l:ne(l,y),[l,h,y]),x=h.trim()!==``&&y.length===0,S=(0,Y.useRef)(null),C=s?be:ye,T=(0,Y.useMemo)(()=>({map:b,expanded:s}),[b,s]),E=w(S,T),D=(0,Y.useMemo)(()=>se(b,C,{moved:u,widths:E,detail:s}),[b,C,s,u,E]),O=b.columns.flat().flatMap(e=>e.nodes),k=O.find(e=>Q(e,n))?.id;je(S,c,{place:k===void 0?void 0:D.nodes[k],sizes:C});let{dragging:A,draggable:M}=ke(D,u,f),{panning:N,pan:P}=ve(`[data-map-node]`),{lit:F,on:I,onLines:L,lights:R}=Ae(D),z={family:c,expanded:s,isMoved:O.some(e=>Object.hasOwn(u,e.id)),showFamily:p,expand:m,tidy:()=>{f({},!0)}},[B,V]=(0,Y.useState)(),H=Me(O.find(e=>e.id===B),i,z),W=s?Fe:Pe,G=e=>L.has(e.link)?2:+(e.from===k||e.to===k),re=[...D.lines].sort((e,t)=>G(e)-G(t));return(0,Z.jsxs)(`div`,{className:`studio-map-frame`,role:`none`,onKeyDown:e=>{e.key===`Escape`&&c!==void 0&&(e.target.closest(`[role="menu"]`)||(e.stopPropagation(),p(void 0)))},children:[(0,Z.jsx)(d,{className:`studio-map-scroll`,axis:`both`,role:`region`,label:`Map`,height:`100%`,overscroll:`allow`,children:(0,Z.jsx)(j,{items:H,label:`Map actions`,"data-map-field":``,children:(0,Z.jsxs)(`div`,{ref:S,className:`studio-map`,"data-lit":F===void 0||A!==void 0?void 0:``,"data-panning":N?``:void 0,onPointerDown:P,onContextMenuCapture:e=>{V(e.target.closest(`[data-map-node]`)?.dataset.mapNode)},style:{"--map-width":`${String(D.width)}px`,"--map-height":`${String(D.height)}px`,"--map-slot":`${String(C.node.width)}px`,"--map-line":`${String(C.card.row)}px`},children:[(0,Z.jsx)(`svg`,{className:`studio-map-lines`,width:D.width,height:D.height,"aria-hidden":`true`,children:re.map(({link:e,from:t,to:n,d:r})=>(0,Z.jsx)(`path`,{className:`map-line`,d:r,"data-kind":e.kind,"data-on":L.has(e)?``:void 0,"data-open":t===k||n===k?``:void 0},`${e.kind}:${e.from}:${e.to}`))}),D.headings.map(({label:e,x:t,y:n})=>(0,Z.jsx)(`div`,{className:`studio-map-heading`,style:{left:t,top:n},children:(0,Z.jsx)(a,{type:`supporting`,color:`secondary`,weight:`semibold`,children:e})},e)),O.map(e=>{let t=D.nodes[e.id];return t&&(0,Z.jsx)(W,{node:e,place:t,joins:ie(b,e.id),selected:n,on:I,isFound:y.includes(e.id),isDragging:A===e.id,onOpen:i,lights:R,drag:M(e.id)},e.id)})]})})}),x&&(0,Z.jsx)(g,{className:`studio-map-nothing`,children:(0,Z.jsx)(ee,{headingLevel:2,icon:(0,Z.jsx)(r,{icon:_,size:`lg`}),title:`Nothing matches`})}),(0,Z.jsx)(Ne,{actions:z,query:h,onQuery:v,onClose:o})]})}export{Ie as StudioMap};
|