@theoremjs/studio 0.3.4-next.508.geda6db0 → 0.3.4-next.524.g5000023

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/compile.js +44 -2
  2. package/draft.d.ts +54 -1
  3. package/draft.js +14 -0
  4. package/mod.d.ts +1 -1
  5. package/mod.js +1 -1
  6. package/package.json +4 -4
  7. package/page/assets/{Banner-BcHZFaJb.js → Banner-CqLOCD6Z.js} +2 -2
  8. package/page/assets/{ConsoleFrame-Byq_hSpu.js → ConsoleFrame-Tjt_zLbG.js} +1 -1
  9. package/page/assets/{ContextMenu-C6S-GYrc.js → ContextMenu-DPqKbw_f.js} +2 -2
  10. package/page/assets/{ToolResultCharts-CkEf5ub5.js → ToolResultCharts-BQwnjoiy.js} +1 -1
  11. package/page/assets/{TraceInspector-BsYHHhGv.js → TraceInspector-C2rlhE71.js} +1 -1
  12. package/page/assets/{TraceOverview-CMFfbfGM.js → TraceOverview-B9V8W-q0.js} +1 -1
  13. package/page/assets/{_virtual_studio-type-sources-CTIGQ210.js → _virtual_studio-type-sources-oXv11QXQ.js} +54 -17
  14. package/page/assets/browser-engine-CywA6yoH.js +11 -0
  15. package/page/assets/browser-transport-CFSkVqTn.js +47 -0
  16. package/page/assets/{compile-egress-BSxOdX4K.js → compile-egress-BRGW9qfO.js} +2 -2
  17. package/page/assets/{crypto-DAIn4qnM.js → crypto-D0sMVyOH.js} +1 -1
  18. package/page/assets/{encode-files-oYzzs_iG.js → encode-files-BvmEyafH.js} +1 -1
  19. package/page/assets/{export-agent-BeUTYowB.js → export-agent-CC6sy8t7.js} +1 -1
  20. package/page/assets/{guardrail-tester-DLT99rnO.js → guardrail-tester-DN3ZAkjj.js} +1 -1
  21. package/page/assets/host-patterns-cSf1U25G.js +1 -0
  22. package/page/assets/{index-DNA-Y8Mp.js → index-escjDtrD.js} +71 -71
  23. package/page/assets/{live-ingress-lDUGPwth.js → live-ingress-qi-y5uvH.js} +1 -1
  24. package/page/assets/{live-messages-BnBioidx.js → live-messages-BfGupbXr.js} +1 -1
  25. package/page/assets/reader-Dwjcmg_e.js +7 -0
  26. package/page/assets/{shaped-data-1Qn2111E.js → shaped-data-yA5pdGCO.js} +15 -11
  27. package/page/assets/{stub-B3GersQP.js → stub-B5Xqezkf.js} +1 -1
  28. package/page/assets/studio-code-pane-TzEXqNrr.js +8 -0
  29. package/page/assets/{studio-console-CJT5FkWm.js → studio-console-CmukeRuA.js} +1 -1
  30. package/page/assets/{studio-decision-DhHdHb7Z.js → studio-decision-DXttPtt-.js} +1 -1
  31. package/page/assets/{studio-embedding-B8vBhuZU.js → studio-embedding-DJCN5JlP.js} +1 -1
  32. package/page/assets/{studio-host-console-CE_5_tEn.js → studio-host-console-DlSXTr46.js} +2 -2
  33. package/page/assets/{studio-labels-C2SI_T2p.js → studio-labels-B6Q2NeFO.js} +1 -1
  34. package/page/assets/studio-live-Cag9FHZu.js +5 -0
  35. package/page/assets/{studio-map-CKm_FCd9.js → studio-map-FtpYQ1kF.js} +1 -1
  36. package/page/assets/{studio-trace-replay-BRMD6pex.js → studio-trace-replay-CC7mjkLh.js} +1 -1
  37. package/page/assets/{studio-type-checker-DoaPHYNy.js → studio-type-checker-DnHx9_mj.js} +1 -1
  38. package/page/assets/tool-schema-Cz7rA_Ff.js +17 -0
  39. package/page/assets/{trace-record-DWxIfO7D.js → trace-record-Czcy5c-7.js} +1 -1
  40. package/page/assets/tree-OAdfOli8.js +3 -0
  41. package/page/assets/{turn-client-DF0ije7A.js → turn-client-B3luhTmk.js} +1 -1
  42. package/page/assets/types-DUW-r0Zo.js +1 -0
  43. package/page/assets/{use-one-call-Bhnpve1Y.js → use-one-call-D3R9z_11.js} +1 -1
  44. package/page/assets/workspace-DBo9uy_h.js +1 -0
  45. package/page/index.html +17 -17
  46. package/read-source.js +10 -1
  47. package/registrations.d.ts +6 -0
  48. package/tools.js +3 -0
  49. package/types.d.ts +6 -0
  50. package/ui/profile-editor.js +21 -5
  51. package/page/assets/browser-engine-DjYv346h.js +0 -11
  52. package/page/assets/browser-transport-Bm3uY9Fj.js +0 -47
  53. package/page/assets/host-patterns-C9RMP16Q.js +0 -1
  54. package/page/assets/reader-BFYIhA73.js +0 -7
  55. package/page/assets/studio-code-pane-CCi7-lyE.js +0 -8
  56. package/page/assets/studio-live-CKSSyYZj.js +0 -5
  57. package/page/assets/tool-schema-DXYwL5aE.js +0 -18
  58. package/page/assets/tree-Chi6mqzx.js +0 -3
  59. package/page/assets/types-2I4NfLiS.js +0 -1
  60. package/page/assets/workspace-U3w2ELtN.js +0 -1
@@ -1,7 +0,0 @@
1
- import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,E as n,O as r,T as i,b as a,d as o,f as s,g as c,l,m as u,o as d,p as f,s as p,u as m,v as h,w as g,x as _,y as v}from"./schemas-BQ9Jydzb.js";import{$n as y,$t as b,An as x,Bn as S,Bt as ee,Dr as te,Fn as C,G as w,Gn as T,Hn as E,Hr as D,In as O,Jt as ne,Kn as k,Lr as re,Mn as ie,Mr as ae,Or as oe,Pn as se,Pr as ce,Qn as le,Qt as ue,Rt as de,Ur as fe,Ut as pe,Vr as me,Wn as he,Xn as ge,Zn as _e,ar as ve,br as ye,dn as A,fn as be,gn as xe,hn as j,ir as Se,jn as Ce,kr as we,lr as Te,mn as Ee,nr as De,or as Oe,pn as M,pr as ke,qn as Ae,qt as je,rr as Me,s as Ne,tn as Pe,tr as Fe,un as Ie,vr as Le,vt as Re,wr as ze,yr as Be,zn as Ve,zr as He}from"./tool-schema-DXYwL5aE.js";import{c as N}from"./host-patterns-C9RMP16Q.js";import{$t as Ue,A as We,An as Ge,B as Ke,Bt as qe,En as Je,Et as Ye,F as Xe,Gt as Ze,Ht as Qe,I as $e,It as et,Jt as tt,Kt as nt,L as rt,Lt as it,M as at,Mn as P,Mt as ot,N as st,Nn as ct,On as lt,P as ut,Pt as dt,Q as ft,Rt as pt,Sn as mt,St as ht,Ut as gt,Vt as _t,W as vt,Wt as yt,X as bt,bt as xt,et as St,ft as Ct,gn as wt,hn as Tt,in as Et,it as Dt,jt as Ot,k as kt,mn as At,mt as F,nt as jt,pn as Mt,rn as Nt,rt as Pt,tt as Ft,ut as It,wn as Lt,wt as Rt,xn as zt,zt as Bt}from"./shaped-data-1Qn2111E.js";import{a as Vt,n as Ht}from"./live-ingress-lDUGPwth.js";import{n as Ut,t as Wt}from"./trace-schema-9CdEyG6Q.js";import{n as Gt}from"./stub-B3GersQP.js";function I(e){return{type:`guardrail`,guardrail:e}}function Kt(e,t,n,r=`redact`,i){if(n.length!==0)return I({stage:e,trust:t,action:r,hits:n,...i?{provenance:i}:{}})}function qt(e,t){return e.type===`guardrail`?{...e,guardrail:wt(e.guardrail,t)}:e}var Jt=65536;function L(e){let t=e.classStarts.length,n=new Uint16Array(Jt);for(let r=0;r<t;r++)n.fill(r,e.classStarts[r],e.classStarts[r+1]??Jt);let r=e.charsets.map(e=>{let n=new Uint8Array(t);for(let t of e)n[t]=1;return n}),i=e.nodes.length,a=new Int32Array(i),o=new Uint8Array(i),s=[];return e.nodes.forEach((e,t)=>{a[t]=e[0],o[t]=e[1],s.push(Int32Array.from(e.slice(2)))}),{classOf:n,has:r,pattern:a,final:o,edges:s,initials:e.initials,leads:e.leads,size:i}}var Yt,R,Xt;async function Zt(){if(Yt)return;let{FORWARD_AUTOMATON:t,REVERSED_AUTOMATON:n}=await e(async()=>{let{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}=await import(`./egress-automata-SiHQTP1i.js`);return{FORWARD_AUTOMATON:e,REVERSED_AUTOMATON:t}},[]);Yt={forward:t,reversed:n}}function Qt(){if(!Yt)throw Error(`A stream was opened before loadEgressAutomata() finished.`);return Yt}var z;function $t(e){let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return e>=128&&n<128?e:n}function en(e){if(!z){z=new Map;for(let e=0;e<Jt;e++){let t=$t(e),n=z.get(t);n?n.push(e):z.set(t,[e])}}return z.get($t(e))??[e]}function tn(e){let t=[0];for(let n of e)t.at(-1)!==n&&t.push(n),n+1<Jt&&t.push(n+1);return t}var nn=new Map;function rn(e){let t=nn.get(e);if(t)return t;let n=Array.from({length:e.length},(t,n)=>en(e.charCodeAt(n))),r=tn([...new Set(n.flat())].sort((e,t)=>e-t)),i=e=>r.indexOf(e),a=L({classStarts:r,charsets:n.map(e=>e.map(i)),initials:[0],leads:[-1],nodes:[...n.map((e,t)=>[0,0,t+1,t]),[0,1]]});return nn.set(e,a),a}function an(e){let t=JSON.stringify(e),n=nn.get(t);if(n)return n;let r=[...new Set(e.flatMap(e=>Array.from(e,e=>e.charCodeAt(0))))];r.sort((e,t)=>e-t);let i=tn(r),a=r.map(e=>[i.indexOf(e)]),o=[],s=L({classStarts:i,charsets:a,initials:e.map((e,t)=>{let n=o.length;for(let n=0;n<e.length;n++)o.push([t,0,o.length+1,r.indexOf(e.charCodeAt(n))]);return o.push([t,1]),n}),leads:e.map(()=>-1),nodes:o});return nn.set(t,s),s}function on(e,t){let n=e.has[0]?.length??0,r=Array.from({length:n},()=>[]);for(let i of t){let t=e.edges[e.initials[i]];for(let i=0;i<t.length;i+=2){let a=e.has[t[i+1]];for(let e=0;e<n;e++)a[e]&&r[e]?.push(t[i])}}return r.map(e=>Int32Array.from(e))}function sn(e,t){e.text+=t,e.fresh+=t}function cn(e){return e.text.length-e.fresh.length}function B(e,t){let n=cn(e);return t>=n?e.fresh.charCodeAt(t-n):e.text.charCodeAt(t)}function ln(e,t,n=e.text.length){let r=cn(e);return t>=r?e.fresh.slice(t-r,n-r):e.text.slice(t,n)}function un(e){let t={text:``,fresh:``,rawAt:e=>e,update(){t.text=e.text,t.fresh=e.fresh}};return t}function dn(e,t){let n={text:``,fresh:``,rawAt:e.rawAt,update(){n.fresh=``,sn(n,t(ln(e,n.text.length)))}};return n}var fn=/\w/,pn=Math.max(...pt.map(e=>e.length));function mn(e){return e.length<=pn+1&&/^[A-Za-z]*$/.test(e)}function hn(e){let t=0,n,r=!1,i=[],a=(e,t,n)=>{sn(o,e);for(let r=0;r<e.length;r++)i.push(t+Math.min(r,n-1))},o={text:``,fresh:``,rawAt:r=>e.rawAt(r<i.length?i[r]:t-(n?.length??0)),update(){o.fresh=``;for(let i=e.text.length;t<i;t++){let i=String.fromCharCode(B(e,t)),o=fn.test(i);o&&!r&&(n=``),r=o,o?n===void 0?a(i,t,1):n+=i:(n!==void 0&&a(Qe(n),t-n.length,n.length),n=void 0,a(i,t,1))}n!==void 0&&!mn(n)&&(a(n,t-n.length,n.length),n=void 0)}};return o}function gn(e){let t={text:``,fresh:``,from:[],rawAt:n=>n<t.from.length?t.from[n]:e(),update(){}};return t}function V(e,t,n){sn(e,t);for(let r=0;r<t.length;r++)e.from.push(n)}var _n=55296,vn=56319,yn=/[A-Za-z]/,bn=56320,xn=57343;function Sn(e){let t=0,n=``,r=[],i=``,a=[],o=!1,s=-1,c=gn(()=>Math.min(t,r[0]??t,a[0]??t,s<0?t:s));function l(e,t){s>=0&&(yn.test(e)||V(c,`\\`,s),s=-1),e===`\\`?s=t:V(c,e,t)}function u(e,t){if(gt(e)&&(o||i)){i+=e;for(let n=0;n<e.length;n++)a.push(t)}else{if(i){if(!yn.test(e))for(let e=0;e<i.length;e++)l(i[e],a[e]);i=``,a=[]}for(let n=0;n<e.length;n++)l(e[n],t);o=yn.test(e)&&e.length===1}}function d(){let e=0;for(;e<n.length;){let t=n.charCodeAt(e),i=t>=_n&&t<=vn;if(i&&e+1>=n.length)break;let a=n.charCodeAt(e+1),o=i&&a>=bn&&a<=xn?2:1;u(n.slice(e,e+o),r[e]),e+=o}n=n.slice(e),r=r.slice(e)}return c.update=()=>{c.fresh=``;let i=e.text.length;for(;t<i;){let a=B(e,t),o=a>=_n&&a<=vn;if(o&&t+1>=i)break;let s=B(e,t+1),c=o&&s>=bn&&s<=xn?2:1,l=yt(ln(e,t,t+c));n+=l;for(let e=0;e<l.length;e++)r.push(t);t+=c}d()},c}var Cn=/[0-9A-Fa-f]/;function wn(e){let t=0,n=-1,r=gn(()=>n<0?t:n);r.update=()=>{r.fresh=``;let a=e.text.length;for(;t<a;){let a=String.fromCharCode(B(e,t));if(n<0){a===`%`?n=t:(V(r,a,t),t++);continue}let o=(t-n)%3;if(o===0?a===`%`:Cn.test(a))t++;else{i(t-o);for(let n=t-o;n<t;n++)V(r,String.fromCharCode(B(e,n)),n)}}};function i(t){t>n&&V(r,Bt(ln(e,n,t)),n),n=-1}return r}var Tn=new Set([`injection`,`base64`,`hex`,`spaced`,`pipe`]),En=new Map(it.map(({pattern:e,hit:t})=>[e,t])),Dn=new Map(Ft.flatMap(({pattern:e,hit:t})=>t?[[e,t]]:[]));function H(e){return{rule:zt(e),severity:`high`,detector:e}}var On=H(`injection`),kn=H(`marker_leak`),An=H(`tool_leak`);function jn({kind:e,group:t}){if(Tn.has(e))return On;switch(e){case`sensitive`:case`card`:return t===void 0?void 0:H(t);case`boundary`:return kn;case`image`:return H(`ungiven_images`);default:return H(`ungiven_links`)}}function Mn(e,t,n){if(e===`card`)return{hit:jt};if(e===`image`||e===`link`){let r=(e===`image`?Pt:Dt).indexOf(t),i=n[e][r];return`find`in i?{find:i.find}:{hit:i.test}}let r=En.get(t)??Dn.get(t);return r?{hit:r}:{}}function Nn(e,{given:t,allow:n,skipImages:r}){let i=e=>({...e,...t?{given:t}:{}}),a={image:It(i(n?.ungiven_images)),link:Ct(i(n?.ungiven_links),r??e.includes(`ungiven_images`))},o=[];return ft.forEach((t,n)=>{let r=jn(t);r?.detector&&e.includes(r.detector)&&o.push({...r,id:n,regex:nt(t.pattern),...Mn(t.kind,t.pattern,a)})}),o}function Pn(){let e=[];return ft.forEach(({kind:t,pattern:n},r)=>{if(t!==`injection`)return;let i=En.get(n);e.push({...On,id:r,regex:nt(n),...i?{hit:i}:{}})}),e}function Fn(){return Ze.map((e,t)=>({...On,id:t,regex:new RegExp(e.source,e.flags)}))}function In(e,t,n){let r=on(t,n.map(e=>e.id)),i=new Int32Array(t.initials.length).fill(-1);n.forEach((e,t)=>{i[e.id]=t});let a=new Int32Array(t.size),o=new Int32Array(t.size),s=new Int32Array(t.size),c=new Int32Array(t.size),l=0,u=new Int32Array(t.size),d=new Int32Array(t.size),f=0,p=0,m=new Uint8Array(n.length),h=new Uint8Array(n.length),g=new Int32Array(n.length),_=new Int32Array(n.length),v=new Uint8Array(n.length),y=Uint8Array.from(n,e=>+!!e.find),b=new Int32Array(n.length).fill(-1),x=new Int32Array(n.length).fill(-1),S=Int32Array.from(n,e=>t.leads[e.id]??-1),ee=[...new Set(S)].filter(e=>e>=0),te=n.flatMap((e,t)=>S[t]<0?[]:[t]),C=new Int32Array(t.has.length).fill(-1);function w(){let{text:n,fresh:h}=e,g=cn(e),{classOf:_,has:v,edges:te,final:w,pattern:T}=t;for(;p<n.length;p++){let e=_[p>=g?h.charCodeAt(p-g):n.charCodeAt(p)];f++;let t=0,E=(e,n)=>{if(d[e]===f){let t=u[e];n<c[t]&&(c[t]=n)}else d[e]=f,u[e]=t,s[t]=e,c[t]=n,t++,w[e]&&(m[i[T[e]]]=1)};for(let t=0;t<l;t++){let n=te[a[t]],r=o[t];for(let t=0;t<n.length;t+=2)v[n[t+1]][e]&&E(n[t],r)}let D=r[e];for(let e=0;e<D.length;e++){let t=D[e],n=i[T[t]],r=S[n],a=r<0?-1:C[r],o=a<0?p:a;E(t,o),y[n]&&(x[n]=p,b[n]<0&&(b[n]=o))}for(let t of ee)v[t][e]?C[t]<0&&(C[t]=p):C[t]=-1;[a,s]=[s,a],[o,c]=[c,o],l=t}}function T(){let n=e.text.length;_.fill(n),v.fill(0);let r=n;for(let e=0;e<l;e++){let n=a[e],s=i[t.pattern[n]],c=o[e];c<_[s]&&(_[s]=c),t.final[n]&&(v[s]=1),c<r&&(r=c)}for(let e of te){let t=C[S[e]];t<0||(t<_[e]&&(_[e]=t),t<r&&(r=t))}return r}function E(t,r){let i=b[t],a=g[t];if(i<0||i>=r){g[t]=r;return}let{find:o,rule:s,severity:c,detector:l}=n[t],u=o?.(e.text,a,r);if(u===void 0)g[t]=r,b[t]=x[t]>=r?r:-1;else return g[t]=Math.max(a,u)+1,{rule:s,severity:c,start:e.rawAt(u),detector:l}}let D={text:``,lower:``},O=()=>(D.text!==e.text&&(D={text:e.text,lower:e.text.toLowerCase()}),D.lower);function ne(t,r){if(!m[t]&&!h[t]){g[t]=r;return}m[t]=0;let i=e.text,{regex:a,hit:o,rule:s,severity:c,detector:l}=n[t];for(a.lastIndex=g[t];;){let n=a.exec(i);if(!n||n.index>=r){g[t]=r,h[t]=n||v[t]?1:0;return}let[u]=n;if(u&&(!o||o(u,i,n.index,O)))return g[t]=a.lastIndex,h[t]=1,{rule:s,severity:c,start:e.rawAt(n.index),detector:l};u||a.lastIndex++,g[t]=a.lastIndex}}function k(){for(let e=0;e<n.length;e++){let t=_[e];if(t<=g[e])continue;let r=n[e].find?E(e,t):ne(e,t);if(r)return r}}return{run(t){w();let n=T();for(let e=k();e;e=k())t.push(e);return e.rawAt(n)}}}var Ln=new WeakMap;function Rn(e){let t=Ln.get(e);return t||(t=L(e),Ln.set(e,t)),t}function zn(e={}){let t={text:``,fresh:``},n=un(t),r=[n],i=(e,t,n)=>(r.includes(e)||r.push(e),In(e,t,n)),a=[],o=e.detect??[],s=Nn(o,e);if(s.length>0&&(R??=L(Qt().forward),a.push(i(n,R,s))),o.includes(`injection`)){R??=L(Qt().forward),Xt??=L(Qt().reversed);let e=Sn(t),r=Pn();a.push(i(n,Xt,Fn()),i(hn(n),R,r),i(e,R,r),i(hn(e),R,r),i(dn(n,_t),R,r),i(dn(n,e=>qe(e)??e),R,r),i(wn(t),R,r))}if(o.includes(`marker_leak`)&&e.note){let t=St(e.note);a.push(i(n,rn(e.note),[{...kn,id:0,regex:t}]))}if(o.includes(`tool_leak`)&&e.tools){let t=vt(e.tools),r=t.map(({regex:e},t)=>({...An,id:t,regex:e}));t.length>0&&a.push(i(n,an(t.map(({literal:e})=>e)),r))}for(let{detector:t,compiled:r,matchers:o}of e.own??[]){let e=o.map(({regex:e},n)=>({...H(t),id:n,regex:new RegExp(e.source,e.flags)}));a.push(i(n,Rn(r.automaton),e))}let c=0;return{push(e){t.text+=e,t.fresh=e;for(let e of r)e.update();let n=[],i=t.text.length;for(let e of a)i=Math.min(i,e.run(n));return c=i,n},holdFrom:()=>c}}function Bn(e,t,n={},r=[]){let i=Xe(e,t).filter(e=>!(rt(e)||r.includes(e))),a=$e(e,t);if(i.length===0&&a.length===0)return;let o=[...i,...a.map(({id:e})=>e)],s=t.sources??{},c=[...i.map(e=>({detector:e,...s[e]})),...a.map(({id:e,matchers:t,compiled:n})=>({detector:e,matchers:t,compiled:n}))],l=c.some(({matchers:e,compiled:t})=>e?.length&&!t),u=zn({detect:i.filter(e=>s[e]?.theorem!==!1),own:c.flatMap(({detector:e,compiled:t,matchers:n=[]})=>t?[{detector:e,compiled:t,matchers:n}]:[]),skipImages:t.ungiven_images[e]!==`ignore`,...n.allow?{allow:n.allow}:{},...n.givenUrls?{given:n.givenUrls}:{},...n.note?{note:n.note}:{},...n.ownTools?{tools:n.ownTools}:{}}),d=a.some(({find:e})=>e),f=e===`live_reply`?96:256,p=``,m=[];return{push(e){p+=e;for(let{start:t,detector:n}of u.push(e))n&&m.push({start:t,detector:n})},holdFrom(){if(l)return 0;let e=u.holdFrom();return d?Math.min(e,Math.max(0,p.length-f)):e},take(r,i,a=!1){let s=m.filter(({start:e})=>e<i);if(s.length===0&&!a&&!d)return{action:`allow`,text:p.slice(r,i),hits:[],taken:i-r};let c={from:r,to:i,settled:s.map(({detector:e})=>e)},l=ut(p,c,e,t,{detectors:o,scope:n});return m=m.filter(({start:e})=>e>=r+l.taken),l}}}function Vn(e){let{context:t}=e,n=e.detect,r=n?Bn(n.boundary,n.matrix,n.scope):void 0,i=e=>n?n.matrix[e][n.boundary]:`block`,a=i(`canary_leak`),o=i(`prompt_leak`),s=t.canaryGiven||a===`ignore`?void 0:t.canary,c=o===`ignore`?void 0:t.privateSystem,l=s!==void 0||c!==void 0,u=l?e.carry??``:``,d=[],f=new Set,p=``,m=0,h=``,g=u.slice(-F),_=u,v=0,y=u,b=0,x=0,S=s?ht(s):void 0;S?.push(u);function ee(e){let n=[];if(S?.push(e)&&n.push([a,Tt]),c){let r=_.length;_+=e;let i=et(_,r);_=_.slice(i),v+=i;let[a]=bt(_,c,t.canary);a&&n.push([o,a])}for(let[e,t]of n)e!==`flag`||f.has(t.rule)||(f.add(t.rule),d.push(t));return n.filter(([e])=>e!==`flag`).map(([,e])=>e)}function te(e){let t=l?ee(e??``):[];return e&&r?.push(e),t.length===0?null:{hits:t,...n?{boundary:n.boundary}:{}}}function C(){let e=s&&a!==`flag`?T(s):h.length,n=c&&o!==`flag`?E(c,t.canary):h.length;return m+Math.min(e,n)}function w(e){if(d.length===0)return e;let t=[...d,...e.found?.hits??[]];return d=[],{...e,found:{action:e.found?.action??`flag`,hits:t}}}function T(e){let t=u.length+m,n=Math.max(t,x),r=Math.max(b,n-F),i=r+xt(y.slice(r-b),e);i<n&&n>t&&(y=g+h,b=t-g.length,i=b+xt(y,e)),x=Math.min(i,u.length+p.length-F);let a=Math.max(b,Math.max(t,x)-F);return y=y.slice(a-b),b=a,Math.max(0,i-t)}function E(e,t){let n=m===0?u:``,r=u.length+m-n.length,[i,a]=v>=r?[_,v]:[n+h,r];return Math.max(0,a+dt(i,e,t)-u.length-m)}function D(e){let t=te(e);if(t)return{blocked:!0,...t};let i=e===void 0,a=i?p.length:Math.min(C(),r?.holdFrom()??p.length),o=Math.max(0,a-m);if(!(n&&r))return w({blocked:!1,emit:O(o)});let s=r.take(m,m+o,i);return s.action===`block`||s.action===`redact`&&!n.rewrite?{blocked:!0,hits:s.hits,boundary:n.boundary}:(O(s.taken),w({blocked:!1,emit:s.text??``,...s.action===`allow`?{}:{found:{action:s.action,hits:s.hits}}}))}function O(e){let t=h.slice(0,e);return h=h.slice(e),m+=t.length,l&&(g=(g+t).slice(-F)),t}return{process(e){return e?(p+=e,h+=e,l&&(y+=e),D(e)):{blocked:!1,emit:``}},flush:()=>D(),accumulated:()=>p,unreleased:()=>h,drainUnreleased:()=>O(h.length),carryOut:()=>l?Ye(u+p,s,c):``}}function U(e,t,n){return st(t,e.detect,n)}async function Hn(e,t,n,r){return U(e,[n],t)?(await Zt(),Un(e,t,n,r)):null}function Un(e,t,n,r){return U(e,[n],t)?Vn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:n===`reply`,scope:Ke(e,t)},...r?{carry:r}:{}}):null}async function Wn(e,t,n,r){return U(e,[n],r??t)?(await Zt(),Vn({context:t,detect:{matrix:e.detect,boundary:n,rewrite:!1,scope:r??Ke(e,t)}})):null}var Gn=class{open;gate;constructor(e){this.open=e}async read(e){if(this.gate===void 0&&(this.gate=await this.open()),this.gate===`stopped`)return``;if(!this.gate)return e;let t=this.gate.process(e);return t.blocked?(this.gate=`stopped`,``):t.emit}end(){if(!this.gate||this.gate===`stopped`)return``;let e=this.gate.flush();return e.blocked?``:e.emit}},Kn=2,qn=4,Jn=3,Yn=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Xn=/^[A-Za-z0-9+/]*={0,2}$/,Zn=new Set([`text/csv`,`text/plain`,`text/markdown`]);function Qn(e){let{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}=e;if(t&&n&&r)return{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}}function $n(e,t){if(t.limitsByMime){let n=j(e);if(t.limitsByMime[n])return t.limitsByMime[n];let[r]=n.split(`/`),i=`${r}/*`;if(t.limitsByMime[i])return t.limitsByMime[i]}return t.maxBytes}function er(e){return`uri`in e}function tr(e){if(e.type===`speech`)throw new N(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new N(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new N(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=Qn(e.inputs??{});if(!t)throw new N(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function nr(e){let t=0;return e.endsWith(`==`)?t=Kn:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Jn/qn)-t}function rr(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function ir(e){return e.replace(Yn,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function ar(e,t,n){let r=rr(t);return e===`text/csv`&&(r=ir(r)),new TextEncoder().encode(n.read(r))}function or(e,t){return t?{...e,fileName:t}:e}function sr(e,t,n){return t.filter(t=>!A(e,t.mimeType)).map(e=>or({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function cr(e,t){let n=[];e.length>t.maxFiles&&n.push({code:`too_many_files`,params:{maxFiles:t.maxFiles}});let r=0;for(let i of e){if(i.sizeBytes===void 0)continue;let e=$n(i.mimeType,t);i.sizeBytes>e&&n.push(or({code:`file_too_large`,params:{maxBytes:e}},i.name)),r+=i.sizeBytes}return r>t.maxTurnBytes&&n.push({code:`turn_too_large`,params:{maxTurnBytes:t.maxTurnBytes}}),n}function lr(e,t,n){let r=[];return t.length>0&&!e.attachments&&r.push({code:`attachments_not_accepted`,params:{channel:`attachment`}}),n.length>0&&!e.voice&&r.push({code:`voice_not_accepted`,params:{channel:`voice`}}),r.length>0||t.length===0&&n.length===0?r:(e.attachments&&r.push(...sr(e.attachments,t,`attachment`)),e.voice&&r.push(...sr(e.voice,n,`voice`)),e.limits?[...r,...cr([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var ur={mime_not_allowed:`attachments.mime_not_allowed`,too_many_files:`attachments.too_many_files`,too_many_of_kind:`attachments.too_many_of_kind`,file_too_large:`attachments.file_too_large`,turn_too_large:`attachments.turn_too_large`,attachments_not_accepted:`attachments.not_accepted`,voice_not_accepted:`attachments.not_accepted`,limits_unconfigured:`attachments.limits_unconfigured`};function dr(e){let t={};for(let[n,r]of Object.entries(e.params??{}))r!==void 0&&(t[n]=r);return e.fileName!==void 0&&(t.fileName=e.fileName),{key:ur[e.code],params:t}}function fr(e,t){let n=dr(e);return P(n.key,n.params,t)}function pr(e){return new N(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(dr)})}function mr(e){if(!Xn.test(e))throw new N(`request`,`attachment data must be base64`);return nr(e)}function hr(e){let t={mimeType:e.mimeType,name:e.name};return er(e)||(t.sizeBytes=mr(e.data)),t}function gr(e,t,n){if(!vr(t,n))return;let r=tr(e),i=lr({attachments:be(e,`attachments`),voice:be(e,`voice`),limits:r},(t??[]).map(hr),(n??[]).map(hr));if(i.length>0)throw pr(i)}function _r(e,t){if(er(e))return e;let{mimeType:n,data:r}=e;if(!Zn.has(j(n)))return e;let i=ar(n,Mt(r),t);return{...e,data:At(i)}}function vr(e,t){return(e?.length??0)>0||(t?.length??0)>0}function yr(e,t,n,r){return gr(e,t,n),{attachments:t?.length?t.map(e=>_r(e,r.attachment)):t,voice:n?.length?n.map(e=>_r(e,r.voice)):n}}var br=`
2
-
3
- `;function xr(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function Sr(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=xr(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function Cr(e,t){let n=Sr(e,t);if(n)throw new N(`config`,n)}function wr(e,t,n){return Cr(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function Tr(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function Er(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:br,private:!0}),t.push(...n));return t}function Dr(e){return e.map(e=>e.text).join(``)}function Or(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:Dr(e),private:t}}function kr(e,t){return Or(Er([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}var Ar=[`user`,`slots`,`repair`,`attachment`,`voice`,`history`,`system`];function jr(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var Mr={client:`untrusted`,server:`assembled`};function Nr(e){return typeof e==`string`?e:JSON.stringify(e)}function Pr(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of k){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(Nr(o));let c=s.found(),l=at(`context`,c);l&&n.push({...l,trust:Mr[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var Fr=/^[A-Za-z0-9._-]+$/;function Ir(e){let t=e?.trim();return t&&Fr.test(t)?t:void 0}function Lr(e,t){if(!e)return e;let n=e.guidance?t.read(e.guidance):void 0;return{previousOutput:t.read(e.previousOutput),rejection:t.read(e.rejection),...n?{guidance:n}:{}}}function Rr(e,t){return e.map(e=>{let n=e.content===void 0?void 0:t.read(e.content),r=e.parts?.map(e=>e.type===`text`?{...e,text:t.read(e.text)}:e);return{role:e.role,...n===void 0?{}:{content:n},...r?{parts:r}:{},...e.tool_calls?{tool_calls:e.tool_calls}:{},...e.tool_call_id?{tool_call_id:e.tool_call_id}:{},...e.name?{name:e.name}:{},...e.metadata?{metadata:e.metadata}:{},...e.reasoning?{reasoning:e.reasoning}:{}}})}function zr(e){return new N(`input`,`guardrails.detect blocked the request at ${e}`,{copy:{key:`detect.blocked`}})}function Br(e,t){let{detect:n}=xe(t.guardrails),r=Je(Ar,e=>We(e,n)),i=e.input??{},a=i.text===void 0?void 0:r.user.read(i.text),o=e.system===void 0?void 0:wr(e.system,`TurnRequest.system`,e=>r.system.read(e)),s=jr(i.slots,r.slots),c=Pr(i.context,()=>We(`context`,n)),l=Lr(i.repair,r.repair),u=i.history?Rr(i.history,r.history):void 0,{attachments:d,voice:f}=i.attachments?.length||i.voice?.length?yr(t,i.attachments,i.voice,r):i,p=[],m;for(let e of Ar){let t=r[e].found(),n=at(e,t);n&&p.push(I(n)),t.action===`block`&&(m??=zr(e))}return p.push(...c.events.map(I)),c.blocked&&(m??=zr(`context`)),{request:{...e,system:o,projectId:Ir(e.projectId),input:{...i,text:a,slots:s,...c.context?{context:c.context}:{},repair:l,history:u,attachments:d,voice:f}},events:p,...m?{refusal:m}:{}}}function Vr(e,t){let{request:n,refusal:r}=Br(e,t);if(r)throw r;return n}function Hr(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function Ur(e,t){return[...new Set([...t.filter(t=>A(e,t)),...e.filter(e=>A(t,e))])]}function Wr(e,t){let n=e.attachments?t?Ur(e.attachments.accept,t.media.flatMap(e=>e.accept)):[...e.attachments.accept]:[],r=(t?.media??[]).flatMap(e=>e.maxPerInput===void 0?[]:[{accept:[...e.accept],max:e.maxPerInput}]);return{text:e.text!==!1,...n.length>0?{attachments:{accept:n}}:{},...e.maxFiles===void 0?{}:{maxFiles:e.maxFiles},...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...e.maxTurnBytes===void 0?{}:{maxTurnBytes:e.maxTurnBytes},...e.limitsByMime===void 0?{}:{limitsByMime:{...e.limitsByMime}},...t?.maxInputs===void 0?{}:{maxInputs:t.maxInputs},...r.length>0?{perInput:r}:{}}}function Gr(e){let t=j(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function Kr(e,t){let n=Qn(e),r=lr({attachments:e.attachments?.accept,...n?{limits:{...n,maxFiles:2**53-1}}:{}},t.flat(),[]);if(n)for(let i of t){i.length>n.maxFiles&&r.push({code:`too_many_files`,params:{maxFiles:n.maxFiles}});for(let t of e.perInput??[])i.filter(e=>A(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:Gr(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}var qr=`final_answer`;function Jr(e){return e.structured!==null&&e.tools.wire.length>0}function Yr(e,t,n){let{structured:r}=t;if(!r||!Jr(t))return e;let i={type:`function`,name:qr,description:P(`structured.answer_tool`,{},n),parameters:r.jsonSchema};return{...e,structured:null,wireTools:[...e.wireTools??[],i]}}function Xr(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function Zr(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function Qr(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function W(e){return`tools`in e?e.tools.allow:[]}function $r(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function ei(e){return`tools`in e?e.tools.parallel:void 0}function ti(e,t,n){return W(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||Zr(i.paths,n.path)})}function ni(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&Zr(r.paths,n.path)}):[]}function ri(e,t){let n=e.get(t);if(n&&n.type!==`builtin`)return{type:`function`,name:n.name,description:n.description,parameters:n.inputSchema}}function ii(e,t){let n=[];for(let r of t){let t=ri(e,r);t&&n.push(t)}return n}function ai(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=ri(e,n);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function oi(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function si(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function ci(e,t,n){return Qr(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function li(e,t,n,r){let i=ti(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:ni(e,t,n,r),o=[...i,...a],s=ci(e,t,o),c=si(e,t,o);return{builtins:s,gated:o,visible:c,executable:c.filter(t=>Xr(e,t)),path:n.path,sessionPermissions:n.sessionPermissions,wire:ii(e,c)}}async function ui(e,t,n,r){let i=li(e,t,n,r);return await fi(e,i,t,n),i}function di(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)}))}}async function fi(e,t,n,r){let i=$r(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new N(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new N(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);for(let n of a){if(!t.gated.includes(n))continue;let r=e.get(n);r?.loadTier===`T2`&&(r.type===`builtin`?oi(e,t,n):ai(e,t,n))}t.executable=t.visible.filter(t=>Xr(e,t))}var pi=new Set([`__proto__`,`constructor`,`prototype`]);function mi(e){if(!kt(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function hi(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||pi.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=_i(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;Zr(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)ai(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>Xr(e,t)),{promoted:a}}function gi(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function _i(e,t,n){if(!W(n).includes(t))return gi(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?gi(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:gi(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):gi(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function vi(e,t){return e.get(t)||{name:t,missing:!0}}function yi(e){let t=new Set;if(e.type===`host`||e.type===`decision`||e.type===`embedding`)return[];for(let n of Object.values(e.models))for(let e of n.builtInTools??[])t.add(e);return[...t]}function bi(e,t){return[...W(t),...yi(t)].map(t=>vi(e,t))}function G(e,t){if(Array.isArray(e)){for(let n of e)G(n,t);return}if(typeof e!=`object`||!e)return;let{properties:n,...r}=e;if(typeof n==`object`&&n)for(let[e,r]of Object.entries(n))t.add(e),G(r,t);for(let e of Object.values(r))G(e,t)}function xi(e,t){let n=bi(e,t);if(n.length===0)return;let r=new Set;for(let e of n)`inputSchema`in e&&G(e.inputSchema,r);return{names:n.map(({name:e})=>e),params:[...r]}}function Si(e){return!e||e.length===0?[]:e.slice(-4)}function Ci(e,t){if(e.length===0)return``;let n=e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`);return`${P(`repair.history_heading`,{count:e.length},t)}\n${n.join(`
4
- `)}\n\n`}function wi(e){let{profile:t,repair:n,history:r}=e,i=n.guidance||P(`repair.default_guidance`,{},t.labels),a=Ci(Si(r),t.labels),o=`${P(`repair.prompt_header`,{},t.labels)}\n\n`;return o+=`${P(`repair.prompt_intro`,{},t.labels)}\n\n`,o+=`${P(`repair.section_previous_output`,{},t.labels)}\n\`\`\`\n${n.previousOutput.trim()}\n\`\`\`\n\n`,o+=`${P(`repair.section_validator_rejection`,{},t.labels)}\n${n.rejection.trim()}\n\n`,i.trim()&&(o+=`${P(`repair.section_repair_guidance`,{},t.labels)}\n${i.trim()}\n\n`),a&&(o+=a),o+=`${P(`repair.section_instructions`,{},t.labels)}\n`,o+=P(`repair.prompt_instructions`,{},t.labels),o}function Ti(e,t){let n=[];return t&&n.push(`structured`),e.type===`image`&&n.push(`image`),e.type===`speech`&&n.push(`speech`),n}function Ei(e,t){let n=Ti(e,t);if(!(n.length<=1))throw new N(`config`,`Profile ${e.id} declares multiple output wire formats (${n.join(`, `)}). Only one of a structured JSON schema (outputs.structured), image, or speech may be active.`)}function Di(e,t){if(e.type!==`speech`){if(t.speech)throw new N(`request`,`Profile ${e.id} (${e.type}) takes no speech settings — only a speech profile speaks`)}else if(t.system)throw new N(`config`,`Profile ${e.id} (speech) takes no system prompt — the input text is the transcript`)}function Oi(e,t){return e.type===`speech`?{...e.speech,...ki(t.speech)}:void 0}function ki(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0))}function Ai(e){if(e.type!==`image`)return null;let t=e.image;return{type:`image`,mimeType:t.mimeType,aspectRatio:t.aspectRatio,resolution:t.resolution,quality:t.quality,background:t.background,n:t.n,seed:t.seed,outputCompression:t.outputCompression,includeText:t.includeText===!0}}function ji(e){let t=Ie(e);if(!t)throw new N(`input`,`MIME '${e}' is not a supported media input type`);return t}function Mi(e){return e.map(e=>{let t=ji(e.mimeType),n=j(e.mimeType),r=n===`image/jpg`?`image/jpeg`:n;return er(e)?{type:t,mimeType:r,uri:e.uri}:{type:t,mimeType:r,data:e.data}})}function Ni(e,t){let{text:n,repair:r,history:i}=t.input??{};if(e.type===`speech`&&!n?.trim())throw new N(`request`,`Profile ${e.id} (speech) requires text input`);if(M(e)?.text===!1&&n)throw new N(`request`,`Profile ${e.id} does not accept text input`);let a=r?wi({profile:e,repair:r,history:i}):Fi(e,t)??n;if(e.type===`speech`)return a?{type:`text`,text:a}:null;let o=[...Pi(t),...a?[ot(a)]:[]];return o.length>0?{type:`text`,text:o.join(`
5
-
6
- `)}:null}function Pi(e){let t=e.input?.context??{};return[...k].reverse().filter(e=>t[e]!==void 0).map(e=>Ot(e,Nr(t[e])))}function Fi(e,t){if(t.continueFrom&&ee.includes(e.type)){if(t.input?.text)throw new N(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return P(`continue.instruction`,{},e.labels)}}function Ii(e){return e.type===`image`&&e.image.references?Mi(e.image.references):[]}function Li(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...Ii(e),...Mi(n),...Mi(r)]}function Ri(e,t){let n=[],r=Ni(e,t);return r&&n.push(r),n.push(...Li(e,t)),n}function zi(e,t){let n=t.input?.slots;if(!n)return;let r=M(e)?.slots??{};for(let[t,i]of Object.entries(n)){let n=Object.hasOwn(r,t)?r[t]:void 0;if(!n)throw new N(`request`,`Profile ${e.id} has no slot '${t}'`);if(!n.includes(i))throw new N(`request`,`Profile ${e.id}: slot '${t}' takes ${n.join(`, `)}, not '${i}'`)}}function Bi(e,t){let n=t.input?.context;if(!n)return;let r=M(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!k.includes(t)||!r?.from.some(e=>e===t))throw new N(`request`,`Profile ${e.id} takes no context from '${t}'`);if(Nr(i).length>r.maxChars)throw new N(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}var Vi=/\{([A-Za-z_][\w-]*)\}/g;function Hi(e,t,n,r){let i=M(e)?.slots;return i?t.replace(Vi,(t,a)=>{if(!Object.hasOwn(i,a))return t;let o=n&&Object.hasOwn(n,a)?n[a]:void 0;if(o===void 0)throw new N(`request`,`Profile ${e.id}: ${r} uses slot '${a}', and the request chose no value for it`);return o}):t}function Ui(e,t){let{handle:n}=e.identity,r=e.type===`speech`?void 0:e.identity.systemByRole;return t&&r&&Object.hasOwn(r,t)?t:n}function Wi(e,t,n){if(e.type===`speech`)return[];let{systemByRole:r,system:i}=e.identity,a=r?.[t]||i||``;return a?Tr(wr(a,`Profile ${e.id} identity.system`,t=>Hi(e,t,n,`identity.system`))):[]}function Gi(e,t){return Er([Wi(e,Ui(e,t.input?.role),t.input?.slots),t.system===void 0?[]:Tr(t.system)])}function Ki(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function qi(e,t){if(Ki(e))return e;throw e.type===`host`?new N(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new N(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new N(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function Ji(e,t){if(t){if(!e.allowModelSelect)throw new N(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new N(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function Yi(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new N(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new N(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new N(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function Xi(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function Zi(e,t){if(e.type===`live`)return null;let n=e.outputs?.structured;if(!n)return null;if(typeof n==`string`)return n;let r=t?.[n.by];if(r){let e=n.map[r];if(e)return e}return n.fallback}function Qi(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function $i(e,t){return e.type===`live`?`live`:`turn`}function ea(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new N(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=ne(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new N(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new N(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new N(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function ta(e,t){return U(xe(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function na(e){let{detect:t}=xe(e.guardrails);return e.type!==`speech`&&Et(t,`canary_leak`)?Rt():``}function ra(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new N(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function ia(e,t,n){let r=qi(e.profiles.get(t.profile),`resolveTurn`);zi(r,t),Bi(r,t);let i=Vr(t,r),a=i.input??{};ea(r,i);let o=n??Ji(r,i.model),s=Ee(r,o),c=li(e.tools,r,i,o),l=c.builtins,u=Zi(r,a.slots);if(Ei(r,u),u&&c.wire.some(e=>e.name===`final_answer`))throw new N(`config`,`Profile ${r.id}: a structured turn answers through '${qr}', so no tool of its own may take that name`);Di(r,i);let d=ra(r,o,s,i.builtInArgs),f=$i(r,s);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,stream:Qi(r),thinking:Yi(r,s,o,i.effort),summaries:Xi(s),maxOutputTokens:s.maxOutputTokens,temperature:s.temperature,builtins:l,builtInArgs:d,sessionId:i.sessionId,tools:c,sessionPermissions:i.sessionPermissions,execution:i.execution,pageExecution:i.pageExecution,history:a.history,maxSteps:r.maxSteps??20,structured:u?{id:u,jsonSchema:e.schemas.get(u).jsonSchema}:null,image:Ai(r),speech:Oi(r,i),live:r.type===`live`?ta(r.live,r.guardrails):void 0,input:Ri(r,i),canary:na(r),resolvedSystem:Gi(r,i),host:i.host}}}function aa(e){return e.type===`image`?e.image:null}function oa(e,t){let n=qi(t,`projectProfile`),{identity:r}=n,i=M(n)??null,a=n.type===`live`?null:n.outputs??null;return{id:n.id,type:n.type,handle:r.handle,models:n.models,defaultModel:n.defaultModel,allowModelSelect:n.allowModelSelect,maxSteps:n.maxSteps,tools:bi(e,n),inputs:i,outputs:a,image:aa(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function sa(e,t){return oa(e.tools,e.profiles.get(t))}function ca(e){return e==null}function K(e){return ca(e)||typeof e!=`object`||Array.isArray(e)?null:e}function la(e){let t=K(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function ua(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function da(e){let t=e.properties;return K(t)??{}}function fa(e,t){return e?`${e}.${t}`:t}function pa(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function ma(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function ha(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(ca(r)){i&&pa(t,s);return}await ma(t,r,a?.[t],o,s);let c=la(n),l=c?K(r):null;c&&l&&await ga(c,l,t,a,o,s)}async function ga(e,t,n,r,i,a){let o=da(e),s=new Set(ua(e)),c=new Set([...Object.keys(o),...s]),l=K(t);for(let e of c)await ha({path:fa(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function _a(e,t,n,r){let i=la(e);if(!i)throw new N(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!K(t)){for(let e of ua(i))pa(e,a);return a}return await ga(i,t,``,n,r,a),a}function va(e,t){let n=e;for(let e of t.split(`.`)){let t=la(n);if(!t)return!1;let r=da(t);if(!Object.hasOwn(r,e)&&!ua(t).includes(e))return!1;n=r[e]}return!0}function ya(e){return e.map(e=>e.error).join(`; `)}function ba(e,t){let n=e;for(let e of t.split(`.`))n=K(n)?.[e];return n}function xa(e,t,n){let[r,...i]=t.split(`.`),a=K(e)??{};return r===void 0?e:{...a,[r]:i.length?xa(a[r],i.join(`.`),n):n}}async function Sa(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=ba(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function Ca(e,t){let n=e;for(let e of t.split(`.`)){let t=la(n);if(!t)return;n=da(t)[e]}let r=K(n);if(r?.type===`array`)return K(r.items)??void 0}var wa=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Ta=new Set([`text`,`image`,`speech`]),Ea=g().regex(/\S/),Da=t({mimeType:g(),data:m(),name:g().optional()}),Oa=t({mimeType:g(),uri:g(),name:g().optional()}),ka=t({voice:g().optional(),style:g().optional(),speed:h().positive().optional()});function Aa(e){return t(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,d(t).optional()])))}var ja=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function Ma(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function Na(e,n){let{inputs:r}=e,a={text:Ea};r?.attachments&&(a.attachments=l(i([Da,Oa])).optional()),r?.voice&&(a.voice=l(Da).optional()),r?.slots&&(a.slots=Aa(r.slots).optional()),e.type===`speech`&&(a.speech=ka.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new N(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new N(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(ja.has(e))throw new N(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return t(a)}var Pa=v({text:g().optional(),structured:n().optional(),removed:l(v({path:g(),reason:g(),item:n()})).optional(),parts:l(ie).optional(),sources:l(O).optional()});function Fa(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function Ia(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function La(e,t){if(!Ta.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!Fa(e))return`it does not take text`;for(let n of W(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(Ia(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function Ra(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new N(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new N(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=La(a,n);if(o)throw new N(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function za(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return W(e).length===0&&!t?`local`:`delegated`}function Ba(e){let t=se(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=de(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function Va(e,t,n){return{...e,type:`agent`,input:t,output:Pa,sources:e=>e.sources??[],...n}}var Ha=256,Ua=18e5,Wa=/^[\x21-\x7E]{1,256}$/;function Ga(e=Date.now){let t=new Map,n=new Map;return{get(n){let r=t.get(n);if(r&&(t.delete(n),!(e()-r.usedAt>Ua)))return t.set(n,{...r,usedAt:e()}),{id:r.id,protocolVersion:r.protocolVersion}},open(r,i){let a=n.get(r);if(a)return a;let o=i().then(n=>{t.delete(r),t.set(r,{...n,usedAt:e()});for(let e of t.keys()){if(t.size<=Ha)break;t.delete(e)}return n}).finally(()=>n.delete(r));return n.set(r,o),o},drop(e,n){t.get(e)?.id===n&&t.delete(e)},clear(){t.clear(),n.clear()}}}function Ka(e){return e!==null&&Wa.test(e)}async function qa(e,t){let n=JSON.stringify([e,Object.entries(t).map(([e,t])=>[e.toLowerCase(),t]).sort(([e],[t])=>e<t?-1:+(e>t))]),r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return[...new Uint8Array(r)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Ja(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function Ya(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&Xa(i,`${n}.properties.${t}`,r)}function Xa(e,t,n){if(!Ja(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&Ya(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&Xa(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&Xa(e,`${t}.${r}[${i}]`,n)})}}function Za(e,t){let n=[];if(Xa(e,`$`,n),n.length>0)throw new N(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function Qa(e,t=`output`){let n=r(e,{target:`draft-7`,io:t});return delete n.$schema,n.type||=`object`,n}function $a(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map($a);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=$a(e[n]));return t}function eo(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new N(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}var to=class{value;constructor(e){this.value=e}};function no(e){return new to(e)}function ro(e){return(t,n)=>{let{page:r}=n;if(r&&`output`in r)return no(r.output);let{labels:i}=n.profile;throw r?.timedOut?Error(P(`tool.page_timed_out`,{},i)):Error(P(`tool.page_no_answer`,{tool:e},i))}}function io(e){let t=Qa(e.input,`input`);Za(t,`input`);let n=Qa(e.output,`output`);Za(n,`output`);let r={activity:{input:t},activityPast:{input:t,output:n},activityFailed:{input:t},request:{input:t}};for(let t of[`activity`,`activityPast`,`activityFailed`,`request`]){let n=e.labels?.[t],i=n?Re(n,r[t]):void 0;if(i)throw new N(`config`,`Tool "${e.name}" ${t} label: ${i}`)}return{inputSchema:t,outputSchema:n}}function ao(e,t){if(t&&(typeof t.service!=`string`||!t.service.trim()))throw new N(`config`,`Tool "${e}" signs in with slot "${t.slot}" but names no service`)}function oo(e,t,n=[]){if(t?.queryParam===void 0)return;let r=t.queryParam.trim()?t.type===`api_key`?t.headerName!==void 0||t.headerPrefix!==void 0?`is set with headerName or headerPrefix; the key goes in one place`:n.includes(t.queryParam)?`"${t.queryParam}" is also one of mapping.queryParams`:void 0:`is set on a '${t.type}' sign-in; only an API key goes in the URL`:`is blank`;if(r)throw new N(`config`,`Tool "${e}" auth.queryParam ${r}`)}function so(e,t){if(t!==void 0&&!(Number.isInteger(t.requests)&&t.requests>0&&Number.isFinite(t.windowMs)&&t.windowMs>0))throw new N(`config`,`Tool "${e}" limit needs a whole number of requests above 0 and a window above 0 ms`)}function co(e,t){if(!(t===void 0||Number.isFinite(t)&&t>0))throw new N(`config`,`Tool "${e}" timeoutMs needs a finite number of ms above 0`)}function lo(e){return eo(e.endpoint),ao(e.name,e.auth),oo(e.name,e.auth,e.mapping?.queryParams),so(e.name,e.limit),co(e.name,e.timeoutMs),{...e,type:`http`,...io(e)}}function uo(e){return ao(e.name,e.auth),oo(e.name,e.auth),{...e,type:`mcp`,...io(e)}}function fo(e){ao(e.name,e.auth),oo(e.name,e.auth);let t=e.answeredBy===`page`?ro(e.name):e.handler;if(typeof t!=`function`)throw new N(`config`,`Tool '${e.name}' needs a handler, or answeredBy: 'page'`);return{...e,handler:t,type:`function`,...io(e)}}function po(e,t,n){if(e.type===`builtin`)return e;if(e.type===`agent`){let r=Ra(e,t,n),i=M(r),a=Na({type:r.type,...i?{inputs:i}:{}},e);return Va(e,a,io({...e,input:a,output:Pa}))}return e.type===`http`?lo(e):e.type===`mcp`?uo(e):fo(e)}function mo(e=()=>void 0){let t=new Map,n=Ga(),r=e=>t.get(e),i=n=>{let i=po(n,e,r);return t.set(i.name,i),i};return{register:i,registerMany:e=>e.map(e=>i(e)),get:r,require(e){let t=r(e);if(!t)throw new N(`config`,`Tool '${e}' is not registered`);return t},has:e=>t.has(e),list:()=>[...t.values()],findProfile:e,reset:()=>{t.clear(),n.clear()},mcpSessions:n}}function ho(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new N(`config`,P(`provider.binding_identity`))}function go(e){To(e.id,e.models),qo(e.id,e.observability),hs(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))Do(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:Eo(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function _o(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new N(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function vo(e,t,n){if(_o(e,t,n,b),ho(e,t,n,`decision`),`retry`in n)throw new N(`config`,`Profile ${e} model '${t}': a decision binding takes no retry; a decision retries only a transient failure, by the kernel's rule`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new N(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function yo(e){let t=e.models?Hr(e.models):void 0;if(!t)throw new N(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);vo(e.id,t,e.models[t])}function bo(e){if(e.inputs.state!==`json`)throw new N(`config`,`Profile ${e.id}: decision inputs.state must be 'json'`);let t=e.inputs.maxStateBytes;if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw new N(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new N(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function xo(e){return yo(e),bo(e),qo(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function So(e){return e===void 0?{}:{parallel:e}}function Co(e){return wo(e.id,e.tools),qo(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...So(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function wo(e,t){if(!Array.isArray(t.allow))throw new N(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function To(e,t){if(Object.keys(t).length===0)throw new N(`config`,`Profile ${e} must declare at least one model`)}function Eo(e,t){let n=t.defaultModel??Hr(t.models);if(!n)throw new N(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new N(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function Do(e,t,n){Oo(e,t,n),_o(e,t,n,Pe),Oo(e,t,n)}function Oo(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new N(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!Oe.includes(i))throw new N(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${Oe.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new N(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new N(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new N(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function ko(e){return{providerContinuation:e.providerContinuation?ze.parse(e.providerContinuation):{},models:e.models,defaultModel:Eo(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function Ao(e,t,n){if(n?.length){for(let r of n)if(!pe(r))throw new N(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function jo(e,t){t&&(Ao(e,`allowContinue`,t.allowContinue),Ao(e,`autoContinue`,t.autoContinue))}function Mo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function No(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>Mo(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var Po=Object.entries(Fe).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function Fo(e){if(!Mo(e))throw new N(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new N(`config`,`Profile definition must set id`);if(!De.find(t=>t===e.type))throw new N(`config`,`Profile ${t}: type must be one of ${De.join(`, `)}`)}function Io(e){let t=e.identity?.handle,n=[[`id`,e.id,64],[`identity.handle`,typeof t==`string`?t:``,32]];for(let[t,r,i]of n)if(!(Array.from(r).length<=i))throw new N(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function Lo(e){let{id:t,type:n}=e,r=e;for(let[e,i]of Po){if(i&&!i.includes(n))continue;let a=Be(e),o=No(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!Mo(e))return!1;let t=e[s];return t==null||t===``}))throw new N(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function Ro(e){let{id:t,type:n}=e;if(n!==`live`&&ye(`inputs`).includes(n)&&e.inputs==null)throw new N(`config`,`Profile ${t}: type '${n}' must set inputs`)}function zo(e){let[t]=Le(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new N(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Bo(e,t){let n=t.turnBehaviour;jo(e,n?.resumption)}function Vo(e,t){let n=t=>new N(`config`,`Profile ${e}: ${t}`),r=t?.maxRetries;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw n(`outputs.validation.maxRetries must be a non-negative integer`)}function Ho(e,t){let n=t=>new N(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Uo.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Uo.join(`, `)}`);Go(t?.blockedReply,n)}var Uo=[`quota`,`detect`,`blockedReply`,`network`,`taint`],Wo=[`onBlock`,`maxRetries`];function Go(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!Wo.includes(e));if(n!==void 0)throw t(`guardrails.blockedReply.${n} is not a setting; it takes onBlock and maxRetries`);let{onBlock:r,maxRetries:i}=e;if(r!==void 0&&!ae.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${ae.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function Ko(e){let t=e.guardrails?.detect,n=e.type===`host`?Nt(`guardrails.detect`,t,Lt):Nt(`guardrails.detect`,t);if(n!==void 0)throw new N(`config`,`Profile ${e.id}: ${n}`)}function qo(e,t){try{let n=Vt(t);if(!Number.isFinite(n.retainForDays))throw new N(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new N(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof N&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new N(`config`,`Profile ${e}: ${n}`)}}function Jo(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`embedding`)return;let{system:t,systemByRole:n}=e.identity;t!==void 0&&Cr(t,`Profile ${e.id} identity.system`);for(let[t,r]of Object.entries(n??{}))Cr(r,`Profile ${e.id} identity.systemByRole.${t}`)}function Yo(e){Fo(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new N(`config`,P(`provider.profile_configuration`,{profile:e.id,field:t}));if(zo(e),Ro(e),Lo(e),Io(e),e.labels&&ct(e.labels,`Profile ${e.id}`),Jo(e),Ko(e),e.type===`host`)return Co(e);if(e.type===`decision`)return xo(e);if(e.type===`embedding`)return go(e);To(e.id,e.models),Bo(e.id,e),Ho(e.id,e.guardrails),e.type===`text`&&Vo(e.id,e.outputs?.validation),qo(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Do(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,system:e.identity.system,systemByRole:e.identity.systemByRole},n=e.guardrails,r=e.observability,i=e.labels,a=ko(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`image`:o={type:`image`,id:e.id,identity:t,...a,image:e.image,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},ts(o.id,o.inputs.attachments?.accept),es(o.id,o.image);break;case`speech`:o={type:`speech`,id:e.id,identity:t,...a,speech:e.speech,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`live`:o={type:`live`,id:e.id,identity:t,...a,live:e.live,inputs:e.inputs,tools:{allow:e.tools.allow,...So(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Ht(o),rs(o.id,o.live.contextCompression),ns(o);break;default:throw new N(`config`,`Unknown profile type '${String(e)}'`)}return Qo(o),Xo(o),Zo(o),o}function Xo(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Zo(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new N(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Qo(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=M(e)?.slots?.[t.by];if(!n)throw new N(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=Object.keys(t.map).filter(e=>!n.includes(e));if(r.length)throw new N(`config`,`Profile ${e.id}: outputs.structured.map maps ${r.join(`, `)}, not a choice of slot '${t.by}'`)}var $o={n:{ok:e=>Number.isInteger(e)&&e>=1,rule:`a whole number of 1 or more`},seed:{ok:Number.isInteger,rule:`a whole number`},outputCompression:{ok:e=>Number.isInteger(e)&&e>=0&&e<=100,rule:`a whole number from 0 to 100`}};function es(e,t){for(let[n,{ok:r,rule:i}]of Object.entries($o)){let a=t[n];if(a!==void 0&&!r(a))throw new N(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(Ie(t.mimeType)!==`image`)throw new N(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(er(t)?t.uri:t.data))throw new N(`config`,`${r} needs its bytes or its uri`)})}function ts(e,t){let n=t?.filter(e=>!A(ge,e));if(n?.length)throw new N(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function ns(e){let{greeting:t,resumed:n,sessionResumption:r}=e.live,i=`Profile ${e.id} live`;if(t!==void 0&&(typeof t!=`string`||!t.trim()))throw new N(`config`,`${i}.greeting must be a prompt; leave it out to wait`);if(!n)return;if(typeof n.prompt!=`string`||!n.prompt.trim())throw new N(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new N(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new N(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function rs(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(is(`${n}.triggerTokens`,r),is(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new N(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function is(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new N(`config`,`${e} must be a whole number above 0`)}function as(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(os(i,r),ss(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new N(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new N(`config`,`${i}: a profile that compacts itself must be a text profile that takes text`);return}let a=e.get(r.profile);if(!a)throw new N(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new N(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function os(e,t){if(t.maxTokens<=0)throw new N(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new N(`config`,`${e}: compactAt must be in (0, 1)`)}function ss(e,t){if(t.previousExchanges<0)throw new N(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new N(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new N(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function cs(e,t){for(let n of W(t))if(e.get(n)?.type===`builtin`)throw new N(`config`,t.type===`host`?`Profile ${t.id} lists builtin '${n}' in tools.allow — type 'host' never runs a model`:`Profile ${t.id} lists builtin '${n}' in tools.allow — declare it on models.*.builtInTools instead`)}function ls(e,t){let n=$r(t)?.t2Loader;if(n){if(!W(t).includes(n))throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new N(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*us(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function ds(e,t){for(let{modelId:n,id:r}of us(t))if(e.get(r)?.type!==`builtin`)throw new N(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function fs(e){let t=e.type===`text`?e.outputs?.structured:void 0;return t?typeof t==`string`?[t]:[...new Set([...Object.values(t.map),t.fallback])]:[]}function ps(e,t){let n=fs(t).map(n=>{let r=e.find(n);if(!r)throw new N(`config`,`Profile ${t.id}: outputs.structured names '${n}', which is not a registered schema; register it before the profile`);return r}),r=t.type===`text`?t.outputs?.validation:void 0,i=Object.keys(r?.fields??{}),a=Object.keys(r?.items??{});if(!i.length&&!a.length)return;if(!n.length)throw new N(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>Ca(t.jsonSchema,e)));if(o.length)throw new N(`config`,`Profile ${t.id}: outputs.validation.items has ${o.join(`, `)}, which no structured schema reaches as a list with an items schema`);let s=i.filter(e=>!n.some(t=>va(t.jsonSchema,e)));if(s.length)throw new N(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function ms(e){let t=M(e)?.context;if(!t)return;let n=k;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new N(`config`,`Profile ${e.id}: inputs.context.from must list ${k.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new N(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function hs(e,t){if(!t)return;let{attachments:n,voice:r,maxFiles:i,maxBytes:a,maxTurnBytes:o,limitsByMime:s}=t,c={maxFiles:i,maxBytes:a,maxTurnBytes:o};if((n||r)&&Object.values(c).some(e=>e===void 0))throw new N(`config`,`Profile ${e} must set maxFiles, maxBytes, and maxTurnBytes`);for(let[e,t]of Object.entries(s??{}))c[`limitsByMime['${e}']`]=t;for(let[t,n]of Object.entries(c))if(n!==void 0&&!(Number.isInteger(n)&&n>0))throw new N(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function gs(e,t,n){let r=new Map,i=i=>{let a=Yo(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,ue(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(cs(e,o),ls(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){ds(e,o),hs(o.id,M(o)),ms(o),ps(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&as(r,o,e,t.compaction)}r.set(o.id,o)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new N(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}var _s=`https://generativelanguage.googleapis.com/v1beta/models`;function vs(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function ys(e){let t;try{t=new URL(e.baseUrl)}catch{throw new N(`config`,`Enter a valid localhost URL.`)}if(![`http:`,`https:`].includes(t.protocol)||![`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname)||t.username||t.password||t.search||t.hash)throw new N(`config`,`Use a localhost URL without credentials, query parameters or a fragment.`);return{baseUrl:t.href.replace(/\/$/,``),fetch:(e,n)=>new URL(e instanceof Request?e.url:String(e)).origin===t.origin?fetch(e,{...n,redirect:`error`,credentials:`omit`}):Promise.reject(new N(`blocked`,`Local requests must stay on the configured origin.`))}}var bs=v({data:l(v({id:g().min(1)}))});async function xs(e,t){let n=ys(e);if(!n?.fetch)throw new N(`config`,`Enter a local endpoint.`);let r=await n.fetch(`${n.baseUrl}/v1/models`,{signal:t,headers:{Accept:`application/json`}});if(!r.ok)throw new N(`network`,`Local model list returned HTTP ${r.status}.`);let i=bs.safeParse(await r.json());if(!i.success)throw new N(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var Ss=`https://openrouter.ai/api/v1/models`,Cs=`https://openrouter.ai/api/v1/embeddings/models`,ws=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Ts=[{id:`liquid/lfm-2.5-embedding-350m:free`,label:`Liquid LFM 2.5 Embedding 350M (free)`},{id:`nvidia/nemotron-3-embed-1b:free`,label:`NVIDIA Nemotron 3 Embed 1B (free)`},{id:`nvidia/llama-nemotron-embed-vl-1b-v2:free`,label:`NVIDIA Llama Nemotron Embed VL 1B v2 (free)`}],Es={text:`text`,image:`image`,speech:`speech`,live:void 0,embedding:void 0},Ds=v({data:l(v({id:g().min(1),name:g().optional(),architecture:v({output_modalities:l(g()).optional()}).optional()}))}),Os=v({data:l(v({id:g().min(1),name:g().optional()}))}),ks=v({models:l(v({name:g().min(1),displayName:g().optional(),supportedGenerationMethods:l(g()).optional()})).optional(),nextPageToken:g().optional()}),As=5;async function js(e,t,n){let r=await fetch(t,{...n,redirect:`error`,credentials:`omit`});if(r.status===400||r.status===401||r.status===403)throw new N(`auth`,`${e} refused the key.`);if(!r.ok)throw new N(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Ms(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Ts:ws];if(e===`openrouter`)return await Ns(t,i,r);if(!i)throw new N(`auth`,`Choose a key to list Gemini models.`);return await Fs(t,i,r)}async function Ns(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Os.safeParse(await js(`OpenRouter`,Cs,r));if(!e.success)throw new N(`bad_response`,`OpenRouter returned an invalid embedding model list.`);return e.data.data.map(e=>({id:e.id,label:e.name??e.id}))}let i=Es[e];if(!i)return[];let a=Ds.safeParse(await js(`OpenRouter`,`${Ss}?output_modalities=${i}`,r));if(!a.success)throw new N(`bad_response`,`OpenRouter returned an invalid model list.`);return a.data.data.filter(e=>e.architecture?.output_modalities?.includes(i)??!0).map(e=>({id:e.id,label:e.name??e.id}))}var Ps={live:`bidiGenerateContent`,embedding:`embedContent`};async function Fs(e,t,n){let r=Ps[e]??`generateContent`,i=[],a;for(let e=0;e<As;e++){let e=new URL(_s);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=ks.safeParse(await js(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new N(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function Is(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function Ls(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}var Rs=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function zs(e){return e.join(`,`)}function Bs(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:zs(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,slots:e?.slots,context:e?.context}}function Vs(e){return{text:e.text,attachments:e.attachments?{accept:e.attachments.accept}:void 0,voice:e.voice?{accept:e.voice.accept}:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxTurnBytes:e.maxTurnBytes,limitsByMime:e.limitsByMime,slots:e.slots,context:e.context}}function Hs(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=lr({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:Qn(Vs(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function Us(e){let t=globalThis.MediaRecorder;if(t===void 0)return;let n=e=>t.isTypeSupported(e),r=e=>e.find(n);return e?.length?r(Rs.filter(t=>A(e,t)))??e.find(n):r(Rs)}var Ws=v({protocol:g(),provider:g(),apiId:g(),options:_(g(),u()).optional(),keySlot:g().optional(),fallbackKeySlot:g().optional(),efforts:_(g(),d(Oe)).optional(),defaultEffort:g().optional(),allowEffortSelect:o().optional(),summaries:o().optional(),maxOutputTokens:h().optional(),temperature:h().optional(),builtInTools:l(g()).optional(),compaction:v({maxTokens:h(),compactAt:h(),previousExchanges:h(),profile:g().optional(),timing:d(T),meter:d(he).optional()}).optional(),limits:v({operationTimeoutMs:h().optional(),connectTimeoutMs:h().optional(),liveStepTimeoutMs:h().optional(),maxWireRecordBytes:h().optional(),maxWireResponseBytes:h().optional(),maxEventBytes:h().optional(),maxStepBytes:h().optional(),maxStepEvents:h().optional(),maxPendingToolCalls:h().optional()}).optional()}),Gs=v({structured:i([g(),v({by:g(),map:_(g(),g()),fallback:g()}),p()]).optional(),streaming:v({mode:d(ve).optional(),streamThoughts:o().optional()}).optional()}),Ks=v(Je(mt,()=>d(Ue))),qs=v(Je(tt,()=>Ks)),Js=v({id:g(),label:g(),actions:Ks,names:l(g()),find:o()}),Ys=v({hosts:l(g()),fromTools:o()}),Xs=v({quota:v({perDay:h()}).optional(),detect:qs,patterns:a(d(tt),v({theorem:o(),names:l(g())})).optional(),host:l(Js).optional(),allow:v({ungiven_images:Ys,ungiven_links:Ys}),blockedReply:v({onBlock:d(ae),maxRetries:h()})}),Zs=i([o(),v({theorem:o(),host:o()})]),Qs=v({record:o(),writeTo:i([c(!1),g()]).optional(),sampleRate:h(),include:v({upstreamLog:o(),outboundWire:o(),evidenceRaw:o(),usage:o(),guardrailDecisions:o(),guardrailMatchPreview:o()}),scrub:v({sensitive:Zs,injection:Zs,canary:Zs}),resource:Wt,retainForDays:h(),rotateAfterMiB:h(),hasOnWriteError:o()}),$s=v({text:o(),attachments:v({accept:l(g()),acceptAttr:g()}).nullable(),voice:v({accept:l(g())}).nullable(),maxFiles:h().optional(),maxBytes:h().optional(),maxTurnBytes:h().optional(),limitsByMime:_(g(),h()).optional(),slots:_(g(),l(g())).optional(),context:v({from:l(d(k)),maxChars:h()}).optional()}),ec=v({allowContinue:l(d(Ae)).optional(),autoContinue:l(d(Ae)).optional(),maxContinues:h().optional()}),tc=v({resumption:ec.optional()}),nc=v({allow:l(g()),page:l(g()),t2Loader:g().optional(),parallel:o().optional()}),rc={providerContinuation:v({history:d([`host`,`stateless`,`provider`]).optional()}).optional(),id:g(),models:_(g(),Ws),defaultModel:g(),allowModelSelect:o().optional(),maxSteps:h().optional(),labels:a(d(lt),g()),guardrails:Xs.optional(),observability:Qs.optional()},ic=i([g(),l(i([g(),t({private:g().min(1)})])).min(1).readonly()]),ac=v({handle:g(),system:ic.optional(),systemByRole:_(g(),ic).optional()}),q=f(`type`,[v({...rc,type:c(`text`),identity:ac,outputs:Gs.optional(),inputs:$s,tools:nc,turnBehaviour:v({resumption:ec.optional(),allowSteering:o().optional(),atStepLimit:d(Se).optional()}).optional(),canStop:c(!0),allowSteering:o()}),v({...rc,type:c(`image`),identity:ac,outputs:Gs.optional(),image:v({aspectRatio:g().optional(),resolution:g().optional(),mimeType:g().optional(),quality:g().optional(),background:g().optional(),n:h().int().min(1).optional(),seed:h().int().optional(),outputCompression:h().int().min(0).max(100).optional(),references:l(i([v({mimeType:g(),data:g(),name:g().optional()}),v({mimeType:g(),uri:g(),name:g().optional()})])).optional(),includeText:o().optional()}),inputs:$s,tools:nc,turnBehaviour:tc.optional(),canStop:c(!0)}),v({...rc,type:c(`speech`),identity:v({handle:g()}),outputs:Gs.optional(),speech:v({voice:g().optional(),style:g().optional(),speed:h().optional(),format:d(Me).optional()}),inputs:$s,turnBehaviour:tc.optional(),canStop:c(!0)}),v({...rc,type:c(`live`),identity:ac,inputs:$s.pick({slots:!0,context:!0}).optional(),live:v({ingress:v({audio:o().optional(),video:o().optional(),text:o().optional()}).optional(),voice:g().optional(),vad:v({activityHandling:d(_e).optional(),startSensitivity:d(y).optional(),endSensitivity:d(le).optional(),prefixPaddingMs:h().optional(),silenceDurationMs:h().optional()}).optional(),sessionResumption:o().optional(),contextCompression:v({triggerTokens:h().optional(),slidingWindow:v({targetTokens:h().optional()})}).optional(),transcription:v({input:o().optional(),output:o().optional()}).optional()}),tools:nc.pick({allow:!0,page:!0}),turnBehaviour:v({allowSteering:o().optional()}).optional()})]);function oc(e){let t=xe(e),{sources:n,host:r,...i}=t.detect;return{quota:t.quota,detect:i,...n?{patterns:Object.fromEntries(Object.entries(n).map(([e,{theorem:t,matchers:n}])=>[e,{theorem:t,names:n.map(({name:e})=>e)}]))}:{},...r?{host:r.map(({id:e,label:t,actions:n,matchers:r,find:i})=>({id:e,label:t,actions:n,names:r.map(({name:e})=>e),find:!!i}))}:{},allow:{ungiven_images:sc(t.allow.ungiven_images),ungiven_links:sc(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function sc(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function cc(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function lc(e){if(!e)return;let t=Vt(e);return{record:t.record,writeTo:cc(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function uc(e){let{greeting:t,resumed:n,...r}=e??{};return r}function dc(e,t){let n=e.tools.filter(e=>`type`in e&&e.type===`function`&&e.answeredBy===`page`).map(e=>e.name);if(t){let e=$r(t),r=ei(t);return{allow:[...W(t)],page:n,...e?.t2Loader?{t2Loader:e.t2Loader}:{},...r===void 0?{}:{parallel:r}}}return{allow:e.tools.filter(e=>!(`type`in e&&e.type===`builtin`)).map(e=>e.name),page:n}}function fc({allow:e,page:t}){return{allow:e,page:t}}function pc(e,t){let n=Bs(e.inputs),r=t?.identity??{handle:e.handle},i=t?oc(t.guardrails):void 0,a=t?lc(t.observability):void 0,o=e.outputs??void 0,s={id:e.id,identity:r,models:e.models,defaultModel:e.defaultModel,allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps,providerContinuation:e.providerContinuation,outputs:o,guardrails:i,observability:a,labels:Ge(t?.labels)};switch(e.type){case`text`:return q.parse({...s,type:`text`,inputs:n,tools:dc(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||je(t)});case`image`:return q.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:dc(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return q.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`live`:return q.parse({...s,type:`live`,live:uc(e.live),...e.inputs?{inputs:{slots:n.slots,context:n.context}}:{},tools:fc(dc(e,t))});default:return e.type}}function mc(e,t){let n=qi(e,`interfaceFromProfile`);return pc(oa(t,n),n)}function hc(e){return s(t=>Ve.safeParse(e(t)).success)}var gc=[`running`,`gate`,`complete`,`error`,`cancel`],_c=s(e=>{let t=Ve.safeParse({type:`tool`,tool:e});if(!t.success||t.data.type!==`tool`||!(`phase`in t.data.tool))return!1;let{phase:n}=t.data.tool;return gc.some(e=>e===n)}),vc=_(g(),n()),yc=v({operationId:g().optional(),name:g(),callId:g(),arguments:vc,draft:g().optional(),reasoning:l(C).optional(),stepId:g().optional(),edited:v({from:vc,to:vc}).optional(),activity:g().optional(),activityPast:g().optional(),outputDraft:g().optional(),state:_c.optional(),startedAt:h().optional(),endedAt:h().optional(),artifacts:l(n())}),bc=v({kind:d(ke),native:g().optional()}),J={id:g()},Y=f(`kind`,[v({...J,kind:c(`user-text`),text:g()}),v({...J,kind:d([`user-attachment`,`user-voice`]),name:g(),mimeType:g(),sizeBytes:h(),data:g().optional()}),v({...J,kind:c(`thought`),text:g()}),v({...J,kind:c(`text`),text:g()}),v({...J,kind:c(`tool`),tool:yc}),v({...J,kind:c(`structured`),value:n(),draft:g().optional()}),v({...J,kind:c(`media`),mimeType:g(),data:g().optional(),url:g().optional(),previewUrl:g().optional()}),v({...J,kind:c(`grounding`),grounding:hc(e=>({type:`grounding`,grounding:e}))}),v({...J,kind:c(`citation`),sources:hc(e=>({type:`citation`,sources:e})),callId:g().optional()}),v({...J,kind:c(`evidence`),evidence:hc(e=>({type:`evidence`,evidence:e}))}),v({...J,kind:c(`guardrail`),guardrail:we}),v({...J,kind:c(`error`),message:g()}),v({...J,kind:c(`turn-done`),stop:bc.optional(),tokens:hc(e=>({type:`tokens`,tokens:e})).optional(),interactionId:g().optional(),compaction:o().optional(),workedMs:h().optional(),endedAt:h().optional()})]),xc=v({type:g()});function Sc(e,t){return Object.hasOwn(e,t)}function Cc(e,t){return e.map(e=>{let n=[...t,...e.path],r=`${n.map(String).join(`.`)||`(root)`} ${e.code}`;return e.code!==`invalid_union`||e.errors.length===0?r:`${r} [${e.errors.map(e=>Cc(e,n)).join(` | `)}]`}).join(`; `)}function wc(e){return Cc(e.issues,[])}function Tc(e,t){return new N(`bad_response`,`${e} failed its wire check: ${wc(t)}`)}function X(e,t,n){let r=e.safeParse(t);if(!r.success)throw Tc(n,r.error);return r.data}function Ec(e){return{type:`malformed`,error:new N(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Dc(e,t){let n=xc.safeParse(t);if(!n.success)return Ec(`a line without a kind failed its wire check: ${wc(n.error)}`);let{type:r}=n.data;if(!Sc(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:Ec(`a '${r}' line failed its wire check: ${wc(i.error)}`)}function Oc(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function kc(e,t){let n=Oc(t);return n?Dc(e,n.value):Ec(`a line is not JSON`)}function Ac(e){let t=Oc(e);if(!t)throw new N(`bad_response`,`a line is not JSON`);return t.value}var jc=v({name:g(),mimeType:g(),data:g()}),Mc=v({slots:_(g(),g()).optional(),context:n().optional(),text:g().optional(),attachments:l(jc).optional(),voice:l(jc).optional()}),Nc=v({gateKind:d(Te).optional(),sessionPermissions:l(g()).optional(),name:g().optional(),input:n().optional(),snapshot:E.optional(),promoted:l(g()).optional(),model:g().optional(),effort:g().optional()}),Z=g().trim().min(1);v({input:Mc,conversation:g().min(1).optional(),model:g().optional(),effort:g().optional(),turnId:Z.optional(),abandon:l(Ce).min(1).optional(),replay:Nc.pick({sessionPermissions:!0}).optional(),transcript:l(Y).optional()});var Pc=[`approve`,`deny`],Fc=i([t({unanswered:c(!0)}),t({output:n()}).refine(e=>`output`in e).transform(e=>({output:e.output}))]);v({gateId:g().min(1),operationId:g().min(1).max(256),decision:d(Pc),input:n().optional(),secret:g().optional(),page:Fc.optional(),conversation:g().min(1).optional(),turnId:Z.optional(),replay:Nc.optional()}),v({turnId:Z,id:Z,inject:l(S).min(1)}),v({turnId:Z});var Ic=v({type:c(`conversation`),ref:g().min(1),posted:c(!0).optional()}),Lc={...x,conversation:Ic},Rc=v({transcript:l(Y),paused:v({events:l(Ve),blocks:l(Y)}).optional()});v({conversation:g().min(1)}),v({conversation:g().min(1),at:h().int().min(-1)}),v({blocks:l(Y)});var zc=v({conversation:g().min(1),view:Rc}),Bc=class extends Error{kind;publicMessage;internalMessage;copy;constructor(e,t,n,r){super(n??t??e),this.name=`TheoremStreamError`,this.kind=e,t&&(this.publicMessage=t),n&&(this.internalMessage=n),r&&(this.copy=r)}};function Vc(e){return e instanceof Bc}function Hc(e){return e?.trim()||void 0}var Uc=v({error:g().optional(),errorKind:oe.optional(),errorCopy:te.optional(),errorInternal:g().optional()}),Wc=Uc;function Gc(e,t){let n=Hc(e.error),r=Hc(e.errorInternal);return new Bc(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function Kc(e){return!Vc(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function qc(e,t){let n=kc(e,t);if(n.type===`error`)throw Gc(Uc.parse(n),`internal`);return n}function Jc(e,t,n){let r=e.split(`
7
- `),i=r.pop()??``;for(let e of r)e.trim()&&n(qc(t,e));return i}async function Yc(e,t,n,r){if(!e.body)throw new N(`bad_response`,`stream reply has no body`);let i=e.body.getReader(),a=new TextDecoder,o=``,s=()=>{i.cancel()};r?.addEventListener(`abort`,s,{once:!0});try{for(;;){me(r);let{done:e,value:s}=await i.read();if(e)break;o=Jc(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(qc(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function Xc(e){let t=typeof e.headers==`function`?await e.headers():e.headers,n=new Headers(t);return n.set(`content-type`,`application/json`),n}async function Zc(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return Gc({errorInternal:`HTTP ${String(e.status)}`},He(e.status))}let i=Uc.safeParse(r);return i.success?Gc({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},He(e.status)):new N(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function Qc(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await Xc(n),credentials:n.credentials??`same-origin`})}catch(e){throw re(e)?e:new N(`network`,ce(e),{cause:e})}}async function $c(e,t,n,r,i={}){await Yc(await el(e,t,i),n,r,i.signal)}async function el(e,t,n){let r=await Qc(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await Zc(r);return r}async function tl(e,t,n={}){await el(e,t,n)}async function Q(e,t,n={}){let r=await Qc(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await Zc(r,t.failed);return Ac(await r.text())}async function nl(e,t,n={}){let{signal:r,...i}=n;return X(Rc,await Q(e,{body:t,signal:r},i),`the conversation`)}async function rl(e,t,n,r){let{signal:i,...a}=n;return X(zc,await Q(e,{body:t,signal:i},a),r)}function il(e,t,n={}){return rl(e,t,n,`the rewound conversation`)}function al(e,t,n={}){return rl(e,t,n,`the started conversation`)}function ol(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}var sl=v({interface:q});function cl(e={}){let t=ol(e.endpoint??`/api/theorem`);return{async describe(n){let r=await Qc(t,{method:`GET`,signal:n},e);if(!r.ok)throw await Zc(r);return X(sl,Ac(await r.text()),`the profile description`).interface},turn:({replay:n,...r},i,a)=>$c(`${t}/turn`,r,Lc,i,{...e,signal:a}),invoke:({replay:n,...r},i,a)=>$c(`${t}/invoke`,r,Lc,i,{...e,signal:a}),conversation:(n,r)=>nl(`${t}/conversation`,n,{...e,signal:r}),rewind:(n,r)=>il(`${t}/rewind`,n,{...e,signal:r}),pageResult:(n,r)=>tl(`${t}/page-result`,n,{...e,signal:r}),steer:n=>tl(`${t}/steer`,n,e),stop:n=>tl(`${t}/stop`,n,e)}}function ll(e,t){if(typeof e==`string`)return e;let n=Array.isArray(e)?e:Object.keys(e);return n.length?ll(n[0],t):t}function ul(e,t,n){return{type:`decision`,identity:{handle:e.identity.handle},contract:e.decision.contract,...e.inputs.maxStateBytes===void 0?{}:{maxStateBytes:e.inputs.maxStateBytes},questions:Object.entries(t).map(([e,t])=>({id:e,type:t.type,labels:t.type===`choice`?Object.keys(t.criteria):t.type===`score`?t.criteria.map((e,t)=>ll(e,String(t))):[],...t.type===`box`&&t.image!==void 0?{image:t.image}:{}})),...n&&Object.keys(n).length>0?{images:n}:{},...e.observability?{observability:{record:Vt(e.observability).record}}:{}}}function dl(e,t){let n=Object.keys(t??{}).find(t=>e&&Object.hasOwn(e,t));if(n!==void 0)throw new N(`request`,`the image ${n} is the host's, so the page's needs another name`);let r={...e,...t};return Object.keys(r).length>0?r:void 0}var $=h().min(0).max(1),fl=_(g(),$),pl=f(`type`,[v({type:c(`choice`),choice:g(),confidence:$,probabilities:fl}),v({type:c(`noul`),noul:$}),v({type:c(`box`),box:v({top:$,bottom:$,left:$,right:$}),confidence:$}),v({type:c(`score`),score:h().nonnegative(),confidence:$,legend:_(g(),g().min(1)),probabilities:fl})]),ml=v({result:v({model:g().min(1),answers:_(g(),pl),usage:v({inputTokens:h().int().nonnegative(),outputTokens:h().int().nonnegative(),costUsd:h().nonnegative().optional()}).optional()}),traces:l(Ut).optional()}),hl=new WeakMap;function gl(e,t){return t.length>0&&typeof e==`object`&&e&&hl.set(e,t),e}function _l(e){return typeof e==`object`&&!!e&&hl.get(e)||[]}var vl=v({traces:l(Ut)});async function yl(e,t,n,r,i){let a=[],o=e=>{let t=vl.safeParse(e);t.success&&(a=t.data.traces)};try{return i(await Q(e,{body:t,signal:n,failed:o},r))}catch(e){throw gl(e,a)}}function bl(e,t,n,r={}){return yl(e,t,n,r,xl)}function xl(e){return X(ml,e,`the decision`)}var Sl=v({interface:v({type:c(`decision`),identity:v({handle:g()}),contract:g(),maxStateBytes:h().optional(),questions:l(v({id:g(),type:d([`choice`,`noul`,`score`,`box`]),labels:l(g()),image:g().optional()})),images:_(g(),v({mimeType:d([`image/png`,`image/jpeg`]),data:g()})).optional(),observability:v({record:o()}).optional()})});function Cl(e={}){let t=(e.endpoint??`/api/decision`).replace(/\/$/,``);return{async describe(n){return X(Sl,await Q(t,{signal:n},e),`the decision description`).interface},decide:(n,r,i)=>bl(`${t}/decide`,{state:n,...i?{assets:i}:{}},r,e)}}function wl(e,t,n={}){let r={name:t.name,description:t.description,category:t.category,access:t.access,paths:t.paths,loadTier:t.loadTier,permission:t.permission,...t.labels?{labels:t.labels}:{}};if(t.type===`agent`){e.register({...r,type:`agent`,profile:t.profile,...t.maxCallsPerTurn===void 0?{}:{maxCallsPerTurn:t.maxCallsPerTurn}});return}let i={...r,input:Ne(t.inputSchema),output:Ne(t.outputSchema)};if(t.type===`http`){e.register({...i,type:`http`,endpoint:t.endpoint,method:t.method,headers:t.headers,mapping:t.mapping,auth:t.auth});return}if(t.type===`mcp`){e.register({...i,type:`mcp`,serverUrl:t.serverUrl,mcpToolName:t.mcpToolName,headers:t.headers,auth:t.auth});return}if(t.answeredBy===`page`){e.register({...i,type:`function`,answeredBy:`page`});return}let a=t.stubResponse||!Object.hasOwn(n,t.name)?void 0:n[t.name],o=t.stubResponse??Gt(t.outputSchema);e.register({...i,type:`function`,handler:a?e=>{try{return Promise.resolve(a(e))}catch(e){return Promise.reject(e instanceof Error?e:Error(String(e)))}}:()=>Promise.resolve(o)})}function Tl(e,t,n){e.registerMany(w);for(let r of t)wl(e,r,n)}function El(e,t,n,r,i){return Tl(e.tools,n,i),r&&t.type!==`live`&&e.schemas.register(r.id,r.spec),e.profiles.register(t),t}function Dl(e){if(e.type===`error`&&e.errorInternal!==void 0){let{errorInternal:t,...n}=e;return{...n,error:t}}if(e.type===`session`&&e.session.kind===`ended`&&e.errorInternal!==void 0){let{errorInternal:t,...n}=e;return{...n,session:{...e.session,message:t}}}if(e.type===`tool`&&e.tool.phase===`error`&&e.tool.failure.error!==void 0){let{failure:t}=e.tool;return{...e,tool:{...e.tool,failure:{...t,error:t.message}}}}return e}function Ol(e){if(e.type!==`error`&&e.type!==`session`&&e.type!==`tool`||e.errorInternal===void 0)return e;let{errorInternal:t,...n}=e;return n}function kl(e){if(e.type!==`guardrail`||!e.guardrail?.errorInternal)return e;let{errorInternal:t,...n}=e.guardrail;return{...e,guardrail:n}}function Al(e){if(e.type!==`evidence`||!e.evidence?.raw)return e;let{raw:t,...n}=e.evidence;return{...e,evidence:n}}function jl(e,t){let n=t?.reader===`builder`?Dl(e):kl(Ol(e));return t?.includeEvidenceRaw||(n=Al(n)),n=qt(n,!1),n}function Ml(e,t){return e.map(e=>jl(e,t))}function Nl(e,t,n){let{error:r=``,errorKind:i,errorCopy:a}=jl(fe(D(e),t),n);return{error:r,errorKind:i,...a?{errorCopy:a}:{}}}var Pl={reader:`builder`};function Fl(e){return e.mode===`demo`?{reader:`visitor`}:Pl}export{La as $,kc as A,Wr as At,Is as B,pr as Bt,Wc as C,ei as Ct,$c as D,Jr as Dt,tl as E,qr as Et,Hs as F,Vr as Ft,to as G,Un as Gt,gs as H,Gn as Ht,vs as I,Br as It,$a as J,zn as Jt,eo as K,U as Kt,xs as L,kr as Lt,Y as M,zr as Mt,mc as N,Pr as Nt,X as O,Yr as Ot,Us as P,Rr as Pt,wa as Q,qt as Qt,Ms as R,Sr as Rt,Gc as S,W as St,Kc as T,hi as Tt,Yo as U,Wn as Ut,Ls as V,mr as Vt,mo as W,Hn as Wt,Ka as X,Kt as Xt,Ga as Y,Zt as Yt,qa as Z,I as Zt,cl as _,xi as _t,Ml as a,Sa as at,il as b,mi as bt,Cl as c,Ca as ct,_l as d,Ji as dt,Na as et,bl as f,sa as ft,Bc as g,Ri as gt,Lc as h,Bi as ht,jl as i,Ma as it,Dc as j,Hr as jt,wc as k,Kr as kt,dl as l,ba as lt,gl as m,Hi as mt,Fl as n,Pa as nt,El as o,_a as ot,yl as p,ia as pt,Qa as q,Bn as qt,Nl as r,Ba as rt,Tl as s,ya as st,Pl as t,za as tt,ul as u,xa as ut,nl as v,di as vt,Vc as w,$r as wt,al as x,ui as xt,Q as y,fi as yt,ys as z,fr as zt};
@@ -1,8 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/studio-monaco-xfyfezQS.js","assets/editor.api-Cd3ViPQa.js","assets/preload-helper-DpV6A1kQ.js","assets/editor-DjpsE8to.css","assets/studio-monaco-CbKf90i6.css","assets/register-CDgivxvX.js","assets/studio-type-checker-DoaPHYNy.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{t as r}from"./preload-helper-DpV6A1kQ.js";import{D as i,Ht as a,Kn as o,T as s,Vt as c,hr as l,k as u}from"./tool-schema-DXYwL5aE.js";import{En as d,Jt as f,Sn as p}from"./shaped-data-1Qn2111E.js";import{S as m,U as h,_ as g,h as _,m as v,v as y,y as b}from"./tree-Chi6mqzx.js";import{r as x}from"./live-ingress-lDUGPwth.js";import{n as S,t as C}from"./types-2I4NfLiS.js";import{n as w}from"./stub-B3GersQP.js";import{F as T,M as E,k as ee,r as te}from"./workspace-U3w2ELtN.js";import{g as ne,q as re}from"./index-DNA-Y8Mp.js";var D=class extends Error{line;column;constructor(e,t,n){super(e),this.line=t,this.column=n}},ie=class{text;of;i=0;line=1;column=1;constructor(e,t=`profile`){this.text=e,this.of=t}get done(){return this.i>=this.text.length}pos(){return{line:this.line,column:this.column}}fail(e){throw new D(e,this.line,this.column)}peek(e=0){return this.text[this.i+e]??``}bump(){let e=this.text[this.i]??``;return this.i+=1,e===`
3
- `?(this.line+=1,this.column=1):this.column+=1,e}skip(){for(;;){let e=this.peek();if(e===` `||e===` `||e===`
4
- `||e===`\r`||e===``)this.bump();else if(e===`/`&&this.peek(1)===`/`)for(;!this.done&&this.peek()!==`
5
- `;)this.bump();else if(e===`/`&&this.peek(1)===`*`){for(this.bump(),this.bump();!this.done&&(this.peek()!==`*`||this.peek(1)!==`/`);)this.bump();this.done&&this.fail(`This comment never closes.`),this.bump(),this.bump()}else return}}starts(e){return this.skip(),this.text.startsWith(e,this.i)}eat(e){if(!this.starts(e))return!1;for(let t=0;t<e.length;t+=1)this.bump();return!0}expect(e){this.eat(e)||this.fail(`Expected '${e}'.`)}ident(){this.skip();let e=this.peek();if(!/^[A-Za-z_$]/.test(e))return;let t=``;for(;/^[A-Za-z0-9_$]/.test(this.peek());)t+=this.bump();return t}expectIdent(){let e=this.ident();return e===void 0&&this.fail(`Expected a name.`),e}peekIdent(){return this.skip(),/^[A-Za-z_$][A-Za-z0-9_$]*/.exec(this.text.slice(this.i))?.[0]}rest(){return this.skip(),this.text.slice(this.i)}};function O(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function k(e){e.skip();let t=e.peek();t!==`'`&&t!==`"`&&e.fail(`Expected a string.`),e.bump();let n=``;for(;!e.done&&e.peek()!==t;){let t=e.bump();if(t!==`\\`){n+=t;continue}let r=e.bump(),i={n:`
6
- `,r:`\r`,t:` `,"\\":`\\`,"'":`'`,'"':`"`};if(r in i)n+=i[r];else if(r===`u`){let t=``;for(let n=0;n<4;n+=1)t+=e.bump();n+=String.fromCharCode(Number.parseInt(t,16))}else n+=r}return e.peek()!==t&&e.fail(`This string never closes.`),e.bump(),n}function ae(e){e.skip();let t=e.pos(),n=``;for(e.peek()===`-`&&(n+=e.bump());/^[0-9.eE+-]/.test(e.peek())&&n.length<64;)n+=e.bump();let r=Number(n);if(!Number.isFinite(r))throw new D(`'${n}' is not a number.`,t.line,t.column);return r}function oe(e,t,n,r){let i=0;for(;!e.done;){if(r()&&i===0)return;let a=e.peek();a===`'`||a===`"`?k(e):(a!==``&&t.includes(a)?i+=1:a!==``&&n.includes(a)&&--i,e.bump())}}function se(e){oe(e,`<([{`,`>)]}`,()=>(e.skip(),e.peek()===`;`||e.peek()===`
7
- `))}function ce(e){oe(e,`{([`,`})]`,()=>e.peek()===`;`),e.peek()===`;`&&e.bump()}function le(e,t,n){e.expect(`{`);let r={};for(;!e.eat(`}`);){e.eat(`...`)&&e.fail(`This file doesn't use spreads.`);let i=e.pos(),a;if(a=e.peek()===`'`||e.peek()===`"`?k(e):e.expectIdent(),a===`__proto__`)throw new D(`'__proto__' sets what an object inherits, not a setting.`,i.line,i.column);if(Object.hasOwn(r,a))throw new D(`'${a}' is set twice.`,i.line,i.column);let o=t?`${t}.${a}`:a;n.push({path:o,line:i.line,column:i.column}),e.expect(`:`),r[a]=F(e,o,n),e.eat(`,`),e.done&&e.fail(`This object never closes.`)}return r}function ue(e,t,n){e.expect(`[`);let r=[],i=0;for(;!e.eat(`]`);){e.eat(`...`)&&e.fail(`This file doesn't use spreads.`),e.skip();let a=e.pos(),o=t?`${t}.${String(i)}`:String(i);n.push({path:o,line:a.line,column:a.column}),r.push(F(e,o,n)),i+=1,e.eat(`,`),e.done&&e.fail(`This array never closes.`)}return r}function de(e,t,n){let[r]=t;return e!==`z.fromJSONSchema`&&n.fail(`The studio reads a schema as JSON Schema: z.fromJSONSchema({ ... }), not '${e}'.`),O(r)||n.fail(`z.fromJSONSchema() needs a schema.`),r}function A(e){return O(e)&&e.kind===`member`}function fe(e,t){return{kind:`member`,object:e,name:t}}function pe(e){if(typeof e.object==`string`)return`${e.object}.${e.name}`;if(A(e.object)){let t=pe(e.object);return t?`${t}.${e.name}`:void 0}}function j(e,t,n){let r=e[0];return O(r)||t.fail(n),r}function me(e,t,n){let r=j(e,t,`registerTool() needs the tool object.`),i=r.type,a=typeof i==`string`&&C.includes(i);if(i!==void 0&&!a){let e=n.findLast(e=>e.path===`type`)??t.pos();throw new D(S,e.line,e.column)}return{kind:`registerTool`,tool:r}}function he(e,t,n,r){if(n.of===`provider`){if(e!==`registerProvider`)return n.fail(`'${e}' isn't part of a provider's code.`);let[r,i={}]=t;return typeof r!=`string`&&n.fail(`registerProvider() needs the definition it registers from.`),(!O(i)||t.length>2)&&n.fail(`registerProvider() takes the definition and its settings.`),{kind:`provider`,definition:r,spec:i}}return e===`compileDetect`?j(t,n,`compileDetect() needs the detect object.`):e===`defineProfile`?j(t,n,`defineProfile() needs the profile object.`):e===`registerTool`?me(t,n,r):e===`registerStructured`?{kind:`registerStructured`,args:t}:e===`registerProfile`||e===`registerProvider`?{kind:e}:n.fail(`'${e}' isn't part of this file.`)}function ge(e,t,n){return(typeof t!=`string`||e.some(e=>typeof e!=`string`))&&n.fail(`.join() here joins lines of one string.`),e.join(t)}function _e(e,t,n){if(e.name===`join`&&Array.isArray(e.object))return ge(e.object,t[0],n);if(e.name===`resolve`&&e.object===`Promise`)return t[0];let r=pe(e);return r?.startsWith(`z.`)?de(r,t,n):n.fail(`This call isn't part of this file.`)}function ve(e,t,n,r){return typeof e==`string`?he(e,t,n,r):(A(e)||n.fail(`This call isn't part of this file.`),_e(e,t,n))}function ye(e){return/^(async\s*)?\(\s*\)\s*=>/.test(e.rest())}function be(e,t,n){return e.peekIdent()===`async`&&e.expectIdent(),e.expect(`(`),e.eat(`)`)||e.fail(`A handler here takes no arguments. It returns a fixed value.`),e.expect(`=>`),F(e,t,n)}var M=class{name;constructor(e){this.name=e}};function N(e){return e instanceof M?e.name:e}function P(e,t,n){return ye(e)?be(e,t,n):Se(xe(e,t,n),e,t,n)}function xe(e,t,n){e.skip();let r=e.peek();if(r===`'`||r===`"`)return k(e);if(r==="`"&&e.fail(`This file doesn't use template strings.`),r===`-`||/^[0-9]/.test(r))return ae(e);if(r===`{`)return le(e,t,n);if(r===`[`)return ue(e,t,n);if(r===`(`){e.bump();let r=P(e,t,n);return e.expect(`)`),r}let i=e.ident();return i===`true`?!0:i===`false`?!1:i===`null`?null:(i===void 0&&e.fail(`Expected a value.`),new M(i))}function F(e,t,n){e.skip();let r=e.pos(),i=P(e,t,n);if(!(i instanceof M))return i;if(i.name!==`undefined`)throw new D(`'${i.name}' is set somewhere else. Write its value here.`,r.line,r.column)}function Se(e,t,n,r){let i=e;for(;;)if(t.eat(`.`)){let e=t.expectIdent();i=fe(N(i),e)}else if(t.eat(`(`)){let e=r.length,a=[];for(;!t.eat(`)`);)a.push(N(P(t,n,r))),t.eat(`,`),t.done&&t.fail(`This call never closes.`);i=ve(N(i),a,t,r.slice(e))}else return A(i)&&t.fail(`This file doesn't stop on a property.`),i}function Ce(e,t){e.expectIdent();let n=e.expectIdent();e.expect(`=`);let r=P(e,``,t.spans);(e.eat(`satisfies`)||e.eat(`as`))&&se(e),e.eat(`;`),e.of===`provider`?e.fail(`A provider's code is its registerProvider() call and nothing else.`):n===`profile`?(O(r)||e.fail(`profile has to be the defineProfile() object.`),t.profile&&e.fail(`This file defines two profiles.`),t.profile=r):n===`questions`?(O(r)||e.fail(`questions has to be an object.`),t.questions=r):n===`images`&&(O(r)||e.fail(`images has to be an object.`),t.images=r)}function we(e,t){let n=P(e,``,t.spans);if(e.eat(`;`),O(n)){if(n.kind===`provider`&&typeof n.definition==`string`&&O(n.spec))t.provider&&e.fail(`This code registers two providers.`),t.provider={definition:n.definition,spec:n.spec};else if(n.kind===`registerTool`){let r=n.tool;O(r)||e.fail(`registerTool() needs the tool object.`),t.tools.push(r)}else if(n.kind===`registerStructured`){let[r,i]=Array.isArray(n.args)?n.args:[];(typeof r!=`string`||!O(i))&&e.fail(`registerStructured() needs an id and a spec.`),t.structured={id:r,spec:i}}}}function I(e,t=`profile`){let n=new ie(e,t),r={tools:[],spans:[]};for(n.skip();!n.done;n.skip())n.peekIdent()===`import`?(n.expectIdent(),ce(n)):(n.peekIdent()===`export`&&n.expectIdent(),n.peekIdent()===`const`?Ce(n,r):we(n,r));return t===`provider`?r.provider||n.fail(`This code needs registerProvider().`):r.profile||n.fail(`This file needs defineProfile().`),r}function L(e,t=``){return typeof e==`string`?e:t}function R(e){return typeof e==`number`?e:null}function Te(e,t){if(e===void 0)return``;if(typeof e==`string`)return e;if(!Array.isArray(e))throw new D(t,1,1);return e.map(e=>{if(typeof e==`string`)return e;if(O(e)&&typeof e.private==`string`)return`{private: ${e.private}}`;throw new D(t,1,1)}).join(``)}function z(e){return e===void 0?``:JSON.stringify(e,null,2)}function Ee(e,t){return T(e)===T(t)}function B(e){return O(e)?JSON.stringify(e,null,2):JSON.stringify(e)}function V(e){return Array.isArray(e)?e.map(e=>{if(!O(e)||typeof e.name!=`string`)throw new D(`A pattern needs a name.`,1,1);return Array.isArray(e.words)?{name:e.name,kind:`words`,pattern:``,flags:``,words:e.words.filter(e=>typeof e==`string`)}:{name:e.name,kind:`pattern`,pattern:L(e.pattern),flags:L(e.flags),words:[]}}):[]}function H(e){return O(e)?e:void 0}function U(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function W(e){return Array.isArray(e)?U(e):void 0}function G(e){return L(e)||void 0}function K(e){return Array.isArray(e)?U(e).join(`
8
- `)||void 0:G(e)}function q(e,t,n){return O(e)?t(e):n}function De(e,t,n){if(!O(n))return;if(Array.isArray(n.names)){e.innocentNames=U(n.names);return}if(!(t in e.allow))return;let r=e.allow[t];r.hosts=U(n.hosts),r.fromTools=n.fromTools!==!1}function Oe(e,t,n){let r=H(n.at)??{};e.detect[t]={...e.detect[t],...r};let i=e.sources[t];i&&(n.theorem===!1&&(i.theorem=!1),i.patterns=V(n.patterns),i.hint=L(n.hint)),De(e,t,n.allow)}function ke(e,t){let n=d(p,()=>`ignore`);return O(t.at)&&Object.assign(n,t.at),{key:e,label:L(t.label),at:n,patterns:V(t.patterns),hint:L(t.hint)}}function Ae(e){let t=g().guardrails;if(!O(e))return t;let n={detect:structuredClone(t.detect),sources:structuredClone(t.sources),allow:structuredClone(t.allow),innocentNames:[...t.innocentNames]},r=[],i=new Set(f);for(let[t,a]of Object.entries(H(e.detect)??{}))O(a)&&(i.has(t)?Oe(n,t,a):r.push(ke(t,a)));let a=H(e.quota),o=H(e.blockedReply),s=H(e.network),c=H(e.taint);return{...t,...n,own:r,quotaEnabled:a!==void 0,quotaPerDay:R(a?.perDay),blockedReplyOnBlock:L(o?.onBlock),blockedReplyMaxRetries:R(o?.maxRetries),allowPrivateNetworks:s?.allowPrivateNetworks===!0,allowedHosts:U(s?.allowedHosts),allowedSchemes:U(s?.allowedSchemes),taintAfterRemoteRead:L(c?.afterRemoteRead),taintRemoteDestination:L(c?.remoteDestination)}}var je={"continue.instruction":(e,t)=>{e.turnBehaviour.continueInstruction=t},"canary.bind_note":(e,t)=>{e.guardrails.canaryBindNote=t},"quota.exhausted":(e,t)=>{e.guardrails.quotaMessage=t},"repair.default_guidance":(e,t)=>{e.outputs.repairGuidance=t},"egress.default_repair_guidance":(e,t)=>{e.guardrails.egressRepairGuidance=t},"egress.refusal":(e,t)=>{e.guardrails.egressRefusal=t}};function Me(e,t){if(!O(t))return;let n={};for(let[r,i]of Object.entries(t)){if(typeof i!=`string`)continue;let t=je[r];t?t(e,i):v[r]||(n[r]=i)}e.labels=n}function Ne(e,t,n,r,i){let a=n??y({modelId:e});if(!O(t))return{...a,modelId:e};let o=O(t.efforts)?Object.entries(t.efforts).map(([e,t])=>({alias:e,level:t})):[],s=O(t.compaction)?t.compaction:void 0,c=L(s?.profile),l=R(t.timeoutMs);return{...a,modelId:e,protocol:L(t.protocol,a.protocol),provider:L(t.provider,a.provider),apiId:L(t.apiId),options:H(t.options)??{},timeoutMs:l,efforts:o,defaultEffort:L(t.defaultEffort),allowEffortSelect:t.allowEffortSelect===!0,summaries:typeof t.summaries==`boolean`?t.summaries:null,maxOutputTokens:R(t.maxOutputTokens),temperature:typeof t.temperature==`number`?t.temperature:null,builtInTools:Array.isArray(t.builtInTools)?t.builtInTools.filter(e=>typeof e==`string`):[],keySlot:L(t.keySlot),fallbackKeySlot:L(t.fallbackKeySlot),compactTiming:L(s?.timing),compactMaxTokens:R(s?.maxTokens),compactAt:typeof s?.compactAt==`number`?s.compactAt:void 0,compactKeep:R(s?.previousExchanges),compactMeter:L(s?.meter),compactWith:c?Pe(c,r,`models.${e}.compaction.profile`,i):``}}function Pe(e,t,n,r){return t?t(e)??X(r,n,`'${e}' is not an agent here, so it can't write this model's summaries.`):``}function Fe(e,t){let n=t.output;if(e===`function`&&O(t.handler)&&O(n)&&!Ee(t.handler,w(n)))return z(t.handler)}function Ie(e){let t=H(e.mapping)??{};return{endpoint:G(e.endpoint),method:G(e.method),headersJson:O(e.headers)?z(e.headers):void 0,pathParams:W(t.pathParams),queryParams:W(t.queryParams),bodyParam:G(t.bodyParam),serverUrl:G(e.serverUrl),mcpToolName:G(e.mcpToolName)}}function Le(e){let t=H(e.auth)??{};return{authType:L(t.type),authSlot:G(t.slot),authService:G(t.service),authHeaderName:G(t.headerName),authHeaderPrefix:typeof t.headerPrefix==`string`?t.headerPrefix:void 0,authQueryParam:G(t.queryParam),authUnauthenticated:L(t.onUnauthenticated),authScopes:W(t.scopes),authClientId:G(t.clientId),authRedirectUri:G(t.redirectUri)}}function Re(e,t,n){let r=t??b(),i=L(e.type,r.toolType),a=H(e.labels)??{},o=L(e.profile),s=e.answeredBy===`page`;return{...r,key:t?.key??m(`tool`),toolName:L(e.name,r.toolName),toolType:i,description:L(e.description),category:L(e.category,`studio`),access:L(e.access,r.access),permission:L(e.permission,r.permission),loadTier:L(e.loadTier,r.loadTier),paths:W(e.paths)??[`*`],inputJson:e.input===void 0?r.inputJson:B(e.input),outputJson:e.output===void 0?r.outputJson:B(e.output),activity:K(a.activity),activityPast:K(a.activityPast),activityFailed:K(a.activityFailed),request:K(a.request),stubOutputJson:s?t?.stubOutputJson:Fe(i,e),answeredBy:s?`page`:void 0,...Ie(e),agentKey:o?n?.(o):void 0,maxCallsPerTurn:R(e.maxCallsPerTurn),...Le(e)}}function ze(e,t){let n=new Map(t.map(e=>[e.id,e]));return Object.entries(e).map(([e,t])=>{let r=n.get(e),i=O(t)?t:{},a=L(i.type,`choice`),o=i.criteria,s=Array.isArray(o)?o.map((e,t)=>({key:r?.criteria[t]?.key??m(`criterion`),label:``,text:L(e)})):O(o)?Object.entries(o).map(([e,t],n)=>({key:r?.criteria[n]?.key??m(`criterion`),label:e,text:L(t)})):[];return{key:r?.key??m(`question`),id:e,type:a,instructions:L(i.instructions),criteria:s,...a===`box`&&L(i.image)?{image:L(i.image)}:{}}})}function Be(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)if(O(n)){if(typeof n.uri==`string`){let e=L(n.name);t.push({key:m(`reference`),uri:n.uri,...e?{name:e}:{}})}else typeof n.data==`string`&&t.push({key:m(`reference`),name:L(n.name),mimeType:L(n.mimeType),data:n.data})}return t}function Ve(e,t){return e?h.filter(n=>!n.optional||n.role===`branch`||!n.profileTypes.includes(e)?!1:n.profilePath in t).map(e=>e.id):g().included}function He(e,t,n,r){let i=[],a=new Set;for(let o of e){let e=Re(o,t.get(L(o.name)),n);if(e.toolName&&a.has(e.toolName)){let t=r.filter(e=>e.path===`name`)[i.length]??{line:1,column:1};throw new D(`'${e.toolName}' is registered twice.`,t.line,t.column)}e.toolName&&a.add(e.toolName),i.push(e)}return i}function Ue(e,t,n){if(t===void 0)return[];let r=n.findLast(e=>e.path===`tools.allow`)??{line:1,column:1};if(!Array.isArray(t))throw new D(`tools.allow has to be a list of tool names.`,r.line,r.column);let i=new Map(e.map(e=>[e.toolName,e])),a=[],o=new Set;for(let[e,s]of t.entries()){let t=n.find(t=>t.path===`tools.allow.${String(e)}`)??r;if(typeof s!=`string`||s.trim()===``)throw new D(`tools.allow names tools.`,t.line,t.column);if(o.has(s))throw new D(`'${s}' is listed twice in tools.allow.`,t.line,t.column);o.add(s);let c=i.get(s);if(!c)throw new D(`'${s}' is in tools.allow, and this file has no registerTool for it.`,t.line,t.column);a.push(c)}return a}function We(e,t,n){let r=H(t.identity)??{},i=r.systemByRole;return{...e,agentId:L(t.id),profileType:n,handle:L(r.handle),system:Te(r.system,`The system prompt has to be text.`),systemByRoleJson:O(i)||Array.isArray(i)?z(i):``}}function Ge(e){return{...O(e.providerContinuation)&&(e.providerContinuation.history===`provider`||e.providerContinuation.history===`stateless`)?{providerHistory:e.providerContinuation.history}:{},defaultModel:L(e.defaultModel),allowModelSelect:e.allowModelSelect===!0,maxSteps:R(e.maxSteps),key:L(e.key),fallbackKey:L(e.fallbackKey)}}function Ke(e){return o.includes(e)}function qe(e){let t=H(e.context);return{text:e.text!==!1,attachmentsAccept:U(H(e.attachments)?.accept),voiceAccept:U(H(e.voice)?.accept),maxFiles:R(e.maxFiles),maxBytes:R(e.maxBytes),maxTurnBytes:R(e.maxTurnBytes),limitsByMimeJson:z(e.limitsByMime),slotsJson:z(e.slots),contextFrom:U(t?.from).filter(Ke),contextMaxChars:R(t?.maxChars)}}function Je(e){return Object.fromEntries(Object.entries(e??{}).map(([e,t])=>[e,H(t)?.onFail===`fix`?`fix`:`drop`]))}function Ye(e,t){let n=t?.id??L(e?.structured),r=H(e?.streaming),i=H(e?.validation);return{mode:n?`structured`:`text`,schemaId:n,schemaJson:z(t?.spec.jsonSchema),streamMode:L(r?.mode),streamThoughts:r?.streamThoughts!==!1,validationEnabled:i!==void 0,maxRetries:R(i?.maxRetries),itemRules:Je(H(i?.items)),repairGuidance:``}}function Xe(e){let t=H(e.resumption),n=Array.isArray(t?.allowContinue)?t.allowContinue:[...c],r=Array.isArray(t?.autoContinue)?t.autoContinue:[...a];return{resumeEnabled:n.length>0||r.length>0,allowContinue:n,autoContinue:r,maxContinues:R(t?.maxContinues),continueInstruction:``,allowSteering:e.allowSteering!==!1,atStepLimit:e.atStepLimit===`answer`?`answer`:`stop`}}function Ze(e){let t=g().observability,n=typeof e.writeTo==`string`&&e.writeTo?e.writeTo:t.destination;return{...t,writeTo:e.writeTo!==!1&&n,destination:n,sampleRate:typeof e.sampleRate==`number`?e.sampleRate:t.sampleRate,include:{...t.include,...H(e.include)},scrub:{...t.scrub,...H(e.scrub)},retainForDays:R(e.retainForDays),rotateAfterMiB:R(e.rotateAfterMiB),resourceJson:z(e.resource)}}function Qe(e){return{aspectRatio:L(e.aspectRatio),resolution:L(e.resolution),mimeType:L(e.mimeType),quality:L(e.quality),background:L(e.background),n:R(e.n),seed:R(e.seed),outputCompression:R(e.outputCompression),includeText:e.includeText===!0,references:Be(e.references)}}function $e(e){return{voice:L(e.voice),style:L(e.style),speed:R(e.speed),format:L(e.format)}}function J(e,t){let n=e[t];return typeof n==`boolean`?n:x(t)}function et(e){let t=H(e.ingress)??{},n=H(e.vad)??{},r=H(e.contextCompression),i=H(r?.slidingWindow),a=H(e.transcription);return{ingressAudio:J(t,`audio`),ingressVideo:J(t,`video`),ingressText:J(t,`text`),voice:L(e.voice),sessionResumption:e.sessionResumption===!0,greeting:L(e.greeting),resumedPrompt:L(H(e.resumed)?.prompt),resumedAfterMs:R(H(e.resumed)?.afterMs),contextCompression:r!==void 0,compressionTriggerTokens:R(r?.triggerTokens),compressionTargetTokens:R(i?.targetTokens),transcriptionInput:a?.input===!0,transcriptionOutput:a?.output===!0,vadActivityHandling:L(n.activityHandling),vadStartSensitivity:L(n.startSensitivity),vadEndSensitivity:L(n.endSensitivity),vadPrefixPaddingMs:R(n.prefixPaddingMs),vadSilenceDurationMs:R(n.silenceDurationMs)}}function tt(e,t,n){let r=R(H(t.profile?.inputs)?.maxStateBytes);return{contract:L(e.contract),maxStateBytes:r,questions:t.questions?ze(t.questions,n.questions):[],images:t.images?nt(t.images,n.images):[]}}function nt(e,t){let n=new Map(t.map(e=>[e.name,e]));return Object.entries(e).map(([e,t])=>{let r=e.replace(/^<|>$/g,``),i=O(t)?t:{};return{key:n.get(r)?.key??m(`image`),name:r,mimeType:L(i.mimeType),data:L(i.data)}})}function rt(e){let t=L(e.type);if(t&&!_.includes(t))throw new D(`'${t}' is not a profile type.`,1,1);return t}var it=[`turnBehaviour.atStepLimit`,`outputs.validation.items.*.onFail`];function at(e,t){for(let n of it){let r=l(n)?.options??[];for(let[i,a]of Y(e,n.split(`.`),[]))a!==void 0&&!r.includes(a)&&X(t,i,`${JSON.stringify(a)} is not one of ${r.map(e=>`'${e}'`).join(`, `)}.`)}}function Y(e,t,n){let[r,...i]=t;return r===void 0?[[n.join(`.`),e]]:O(e)?(r===`*`?Object.keys(e):[r]).flatMap(t=>Y(e[t],i,[...n,t])):[]}function ot(e,t,n){let r=e.profile??{},i=rt(r);at(r,e.spans);let a=new Map(t.modelBindings.map(e=>[e.modelId,e])),o=new Map(t.toolSpecs.map(e=>[e.toolName,e])),s=H(r.tools)??{},c=H(r.inputs),l=H(r.outputs),u={...t,identity:We(t.identity,r,i),included:Ve(i,r),models:Ge(r),modelBindings:Object.entries(H(r.models)??{}).map(([t,r])=>Ne(t,r,a.get(t),n,e.spans)),tools:{t2Loader:L(s.t2Loader),parallel:s.parallel===!0},toolSpecs:[],inputs:c&&i!==`decision`?qe(c):t.inputs,outputs:l||e.structured?Ye(l,e.structured):t.outputs,turnBehaviour:q(r.turnBehaviour,Xe,t.turnBehaviour),guardrails:q(r.guardrails,Ae,t.guardrails),observability:q(r.observability,Ze,t.observability),image:q(r.image,Qe,t.image),speech:q(r.speech,$e,t.speech),live:q(r.live,et,t.live),decision:q(r.decision,n=>tt(n,e,t.decision),t.decision),labels:{}},d=He(e.tools,o,n,e.spans),f=Ue(d,s.allow,e.spans);u.toolSpecs=f;let p=new Set(f.map(e=>e.toolName));return u.tools.t2Loader&&!p.has(u.tools.t2Loader)&&(u.tools={...u.tools,t2Loader:``}),Me(u,r.labels),{draft:u,registered:d}}function st(e,t,n){try{let r=I(e),{draft:i,registered:a}=ot(r,t,n);return{ok:!0,draft:i,spans:r.spans,registered:a}}catch(e){if(e instanceof D)return{ok:!1,errors:[{message:e.message,line:e.line,column:e.column}]};throw e}}function X(e,t,n){let r=e.findLast(e=>e.path===t)??{line:1,column:1};throw new D(n,r.line,r.column)}var ct=new Set([`id`,`connection`,`keySlot`,`fallbackKeySlot`]);function lt(e,t,n){let{spec:r}=e;for(let e of Object.keys(r))ct.has(e)||X(n,e,`'${e}' isn't a provider setting the studio holds.`);r.id!==t.id&&X(n,`id`,`The id stays '${t.id}': models and code name the provider by it.`);let a=i(e.definition);if(!a){let t=u().flatMap(e=>s(e)??[]).join(`, `);X(n,``,`'${e.definition}' isn't one of the kernel's providers: ${t}.`)}let o=r.connection===void 0?{}:ut(r.connection,n),c=Object.keys(o).length===0&&t.connection===void 0,l={id:t.id,definition:a,...c?{}:{connection:o}};for(let e of[`keySlot`,`fallbackKeySlot`]){let t=r[e];t!==void 0&&(typeof t!=`string`&&X(n,e,`${e} names a key slot.`),l[e]=t)}return l}function ut(e,t){let n=`connection holds text settings here.`,r={};O(e)||X(t,`connection`,n);for(let[i,a]of Object.entries(e))typeof a!=`string`&&X(t,`connection`,n),r[i]=a;return r}function dt(e,t){try{let n=I(e,`provider`);if(!n.provider)throw new D(`This code needs registerProvider().`,1,1);return{ok:!0,provider:lt(n.provider,t,n.spans),spans:n.spans}}catch(e){if(e instanceof D)return{ok:!1,errors:[{message:e.message,line:e.line,column:e.column}]};throw e}}var Z=e(n(),1),Q=t(),ft=300,pt=2e3;function mt({editor:e,monaco:t,spans:n,errors:r},i){let a=e?.getModel();t&&a&&t.editor.setModelMarkers(a,`studio`,[...r.map(e=>$(t,e.line,e.column,e.message)),...gt(t,n,i)])}function ht({text:e,hold:t,isReadOnly:n=!1,issues:i,onApply:a}){let o=(0,Z.useRef)(null),s=(0,Z.useRef)(a),c=(0,Z.useRef)(e),l=(0,Z.useRef)(n);l.current=n;let u=(0,Z.useRef)(i),d=(0,Z.useRef)({spans:[],errors:[],setting:!1,dirty:!1});return s.current=a,c.current=e,u.current=i,(0,Z.useEffect)(()=>{let e=o.current;if(!e)return;let t={disposed:!1},n,i,a=0,f,p=!1,m=!1,h=()=>{a+=1,i&&clearTimeout(i),i=void 0,f?.stop(),f=void 0,p=!1,m=!1},g=t=>e.contains(t)?!0:t instanceof Element&&!!t.closest(`.suggest-widget, .parameter-hints-widget, .monaco-hover, .monaco-menu-container, .context-view`),_=()=>!!document.querySelector(`.suggest-widget.visible, .parameter-hints-widget.visible`),v,y=()=>{mt(d.current,u.current)};return(async()=>{let o=await r(()=>import(`./studio-monaco-xfyfezQS.js`),__vite__mapDeps([0,1,2,3,4]));await r(()=>import(`./register-CDgivxvX.js`),__vite__mapDeps([5,2,1,3]));let u=(await r(async()=>{let{default:e}=await import(`./editor.worker-6GY8RhDc.js`);return{default:e}},[])).default;if(self.MonacoEnvironment={getWorker(){return new u}},t.disposed||!e.isConnected)return;let b=document.documentElement.dataset.theme===`dark`||globalThis.matchMedia(`(prefers-color-scheme: dark)`).matches,x=o.Uri.parse(`file:///agent.ts`);o.editor.getModel(x)?.dispose();let S=o.editor.createModel(c.current,`typescript`,x),C=o.editor.create(e,{model:S,readOnly:l.current,language:`typescript`,theme:b?`vs-dark`:`vs`,minimap:{enabled:!1},fontSize:13,wordWrap:`on`,wrappingIndent:`indent`,scrollBeyondLastLine:!1,automaticLayout:!0,fixedOverflowWidgets:!0,tabSize:2,padding:{top:12},quickSuggestions:{other:!0,comments:!1,strings:!0},suggestOnTriggerCharacters:!0,acceptSuggestionOnEnter:`on`,tabCompletion:`on`,wordBasedSuggestions:`currentDocument`,parameterHints:{enabled:!0},suggest:{preview:!0,showIcons:!0}});d.current.editor=C,d.current.monaco=o;let w=()=>{i&&clearTimeout(i),i=setTimeout(()=>{t.disposed||(_()?w():h())},pt)},T=()=>{if(f){m&&w();return}if(p)return;let e=a,n=()=>t.disposed||e!==a;p=!0,r(async()=>{let{openTypeChecker:e}=await import(`./studio-type-checker-DoaPHYNy.js`);return{openTypeChecker:e}},__vite__mapDeps([6,2])).then(({openTypeChecker:r})=>{if(n())return;let i=r(o,C,()=>{t.disposed||e!==a||(m=!0,w())});n()?i.stop():f=i}).catch(()=>{}).finally(()=>{e===a&&(p=!1)})};C.onKeyDown(e=>{let t=e.browserEvent;t.metaKey||t.ctrlKey||t.altKey||m&&w()});let E=e=>{let t=e.target;t instanceof Node&&!g(t)&&h()};document.addEventListener(`pointerdown`,E,!0),v=()=>{document.removeEventListener(`pointerdown`,E,!0)},C.onDidBlurEditorText(()=>{queueMicrotask(()=>{if(t.disposed||C.hasTextFocus())return;let e=document.activeElement;e&&g(e)||h()})}),C.onDidChangeModelContent(()=>{if(d.current.setting)return;T();let e=C.getValue();d.current.dirty=e!==c.current,n&&clearTimeout(n),n=setTimeout(()=>{let t=s.current(e);d.current.spans=t.spans,d.current.errors=t.errors,y()},ft)}),y()})(),()=>{t.disposed=!0,v?.(),h(),n&&clearTimeout(n);let e=d.current.editor?.getModel();d.current.editor?.dispose(),e?.dispose(),d.current.editor=void 0}},[]),(0,Z.useEffect)(()=>{let{editor:n}=d.current;n&&!t&&(d.current.dirty&&n.getValue()!==e||(n.getValue()===e||(d.current.setting=!0,n.setValue(e),d.current.setting=!1),d.current.dirty=!1))},[e,t]),(0,Z.useEffect)(()=>{d.current.editor?.updateOptions({readOnly:n})},[n]),(0,Z.useEffect)(()=>{mt(d.current,i)},[i]),(0,Q.jsx)(`div`,{ref:o,className:`studio-fill`})}function $(e,t,n,r){return{startLineNumber:t,startColumn:n,endLineNumber:t,endColumn:n+1,message:r,severity:e.MarkerSeverity.Error}}function gt(e,t,n){return n.flatMap(n=>{let r=n.field?`${n.nodeId}.${n.field}`:n.nodeId,i=t.find(e=>e.path===r)??(n.field?t.find(e=>e.path===n.field):void 0);return i?[$(e,i.line,i.column,n.message)]:[]})}function _t({source:e,blocked:t,issues:n,state:r}){let i=(0,Z.useRef)(e);e&&(i.current=e);let a=(0,Z.useCallback)(e=>{let t=te(r.workspace,r.focus);if(!t)return{errors:[{message:`No agent is open.`,line:1,column:1}],spans:[]};let n=st(e,{...t,toolSpecs:r.workspace.toolSpecs},e=>r.workspace.agents.find(t=>t.identity.agentId.trim()===e)?.key);return n.ok?(r.update(e=>ee(e,r.focus,n.draft,n.registered)),{errors:[],spans:n.spans}):{errors:n.errors,spans:[]}},[r]);return i.current?(0,Q.jsx)(`div`,{className:`studio-fill`,children:(0,Q.jsx)(ht,{text:e??i.current,hold:e==null,issues:n,onApply:a})}):(0,Q.jsx)(ne,{title:`No code yet`,description:`${t??``} to generate the TypeScript.`})}function vt({provider:e,issues:t,state:n,isEditable:r}){let i=(0,Z.useCallback)(t=>{let r=n.workspace.providers.find(t=>t.id===e.id);if(!r)return{errors:[{message:`No provider is open.`,line:1,column:1}],spans:[]};let i=dt(t,r);return i.ok?(n.update(e=>E(e,i.provider)),{errors:[],spans:i.spans}):{errors:i.errors,spans:[]}},[n,e.id]);return(0,Q.jsx)(`div`,{className:`studio-fill`,children:(0,Q.jsx)(ht,{text:re(e),hold:!1,isReadOnly:!r||s(e.definition)===void 0,issues:t,onApply:i},e.id)})}export{_t as CodeBody,vt as ProviderCode};
@@ -1,5 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,l as n,n as r,u as i}from"./themeProps-3IqahpCr.js";import{h as a}from"./tokens.stylex-DkHf0P9C.js";import{i as o,l as s,u as c}from"./SegmentedControlItem-BLuJOusN.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{F as f,M as p,W as m,b as h,s as g,t as _}from"./browser-transport-Bm3uY9Fj.js";import{t as v}from"./mergeProps-ptS-gIMz.js";import{p as y}from"./fieldParts-Cs6Amprh.js";import{t as b}from"./Icon-ZfFwTt8n.js";import{p as x,r as S,t as C,u as ee}from"./IconButton-CG5klqF1.js";import{d as w,f as T,h as E,o as D,u as O}from"./use-trace-records-BkAYJz0M.js";import{t as k}from"./Text-BsiAsowd.js";import{a as A,n as j,t as M}from"./labels-provider-Gus3heEH.js";import{t as N}from"./Dialog-BDUExlk_.js";import{t as P}from"./createReactComponent-CZwsv6DD.js";import{a as F,i as I,t as L}from"./Banner-BcHZFaJb.js";import{t as R}from"./Center-nHS1JSux.js";import{_ as z,g as B,m as te,n as ne,r as re,t as ie,v as ae,y as oe}from"./studio-labels-C2SI_T2p.js";import{Pr as V}from"./tool-schema-DXYwL5aE.js";import{c as H}from"./host-patterns-C9RMP16Q.js";import{Mn as se,mn as ce,pn as le}from"./shaped-data-1Qn2111E.js";import{S as ue,g as de,r as fe,t as pe}from"./reader-BFYIhA73.js";import{i as U}from"./live-ingress-lDUGPwth.js";import{i as me,v as he}from"./turn-client-DF0ije7A.js";import{r as ge,t as _e}from"./live-messages-BnBioidx.js";import{t as ve}from"./EmptyState-C8W4JKBZ.js";import"./use-second-ticker-VX91zrxj.js";import{t as ye}from"./Section-DJ97F7QE.js";import{P as be,S as xe,bt as Se,dt as Ce,i as we,lt as Te,nt as Ee,p as De,ut as Oe}from"./index-DNA-Y8Mp.js";var ke=P(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),Ae=P(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),je=P(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),Me=P(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Ne=P(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),Pe=P(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),Fe=P(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Ie(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 Le(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Re(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 ze(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}function Be(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 Ve=`mic-capture-processor`;function He(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function Ue(e,t,n=16e3){if(t===n)return We(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]=W(i>0?n/i:0),o++,s=t}return a}function We(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=W(e[n]??0);return t}function W(e){let t=Math.max(-1,Math.min(1,e));return t<0?t*32768:t*32767}function Ge(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=new Float32Array(e.byteLength/2);for(let e=0;e<n.length;e++){let r=t.getInt16(e*2,!0);n[e]=r/(r<0?32768:32767)}return n}function G(e){return JSON.stringify(e)}function Ke(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var qe=.05,Je=[500,1e3,2e3,4e3,8e3];function K(e){return e instanceof Error?e:new H(`internal`,V(e),{cause:e})}function q(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function Ye(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function Xe(e){let t=Te(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return Le({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:qe})}function Ze(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var Qe=class{ws=null;audioContext=null;micStream=null;micSource=null;micWorklet=null;micWorkletModuleLoaded=!1;playbackNodes=[];playbackBus=null;playbackAnalyser=null;playbackMeterFrame=0;playbackMeterBuffer=null;nextPlaybackTime=0;status=`disconnected`;serverWorking=!1;micActivating=!1;connectTimeout=null;isMuted=!1;options;inboundChain=Promise.resolve();audioChain=Promise.resolve();toolChain=Promise.resolve();audioEpoch=0;pendingExecuteResults=new Map;context;sentContext;history=[];providerState;sessionOver=!1;droppedAt;lostAt;reconnectTries=0;reconnectTimer=null;constructor(e){this.options=e,this.context=e.context}setStatus(e){this.status=e,(e===`listening`||e===`disconnected`||e===`error`)&&this.clearConnectTimeout(),this.options.onStatusChange?.(e)}get opening(){return this.status===`connecting`||this.status===`reconnecting`}setConnectPhase(e){this.options.onConnectPhase?.(e)}clearConnectTimeout(){this.connectTimeout&&=(clearTimeout(this.connectTimeout),null)}detachWebSocket(){for(let[e,t]of this.pendingExecuteResults)t.reject(new H(`network`,`live session closed before call ${e} settled`));if(this.pendingExecuteResults.clear(),this.ws){this.ws.onopen=null,this.ws.onmessage=null,this.ws.onclose=null,this.ws.onerror=null;try{this.ws.close()}catch{}this.ws=null}}clearReconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectTries=0,this.droppedAt=void 0}teardownConnection(){this.clearConnectTimeout(),this.micActivating=!1,this.setConnectPhase(null),this.detachWebSocket(),this.cleanupAudio()}failSession(e){this.status!==`error`&&this.status!==`disconnected`&&(this.clearReconnect(),this.teardownConnection(),this.options.onError?.(e),this.setStatus(`error`))}createSocket(e){return this.options.createSocket?.()??new WebSocket(e)}connect(){let e=this.lostAt;return this.clearReconnect(),this.lostAt=void 0,e===void 0?(this.providerState=void 0,this.history=[]):this.droppedAt=e,this.open(`connecting`)}startOver(){return this.status!==`connecting`||!this.providerState?!1:(this.providerState=void 0,this.droppedAt=void 0,this.open(`connecting`),!0)}openMessage(){let{slots:e,openMessage:t}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{slots:e}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...t?{host:t}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=Je[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new H(`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 H(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new H(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new H(`network`,`live socket error`))}}catch(e){this.failOpen(new H(`internal`,V(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=Be(e);this.failSession(new H(t?`auth`:`internal`,V(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=Ue(e,t,16e3),r=ce(new Uint8Array(n.buffer)),i=this.ws;i?.readyState===WebSocket.OPEN&&i.send(G({type:`audio`,data:r}))}reportMicVolume(e){this.isMuted||this.options.onVolumeLevel?.(Oe(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),Xe({isMuted:this.isMuted,wsOpen:this.ws?.readyState===WebSocket.OPEN,hasPlaybackNodes:this.playbackNodes.length>0,status:this.status,inputFloat32:e})){let t=this.audioContext?this.audioContext.sampleRate:48e3;this.sendMicFrame(e,t)}}async setupMicrophonePipeline(){if(!this.micStream||!this.audioContext)return;this.micSource=this.audioContext.createMediaStreamSource(this.micStream);let e=this.audioContext.createGain();e.gain.value=0,this.micWorkletModuleLoaded||=(await this.audioContext.audioWorklet.addModule(He()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Ve),this.micWorklet.port.onmessage=e=>{let t=new Float32Array(e.data);this.forwardMicBuffer(t)},this.micSource.connect(this.micWorklet),this.micWorklet.connect(e),e.connect(this.audioContext.destination)}ensurePlaybackBus(){this.audioContext&&!this.playbackBus&&(this.playbackBus=this.audioContext.createGain(),this.playbackAnalyser=this.audioContext.createAnalyser(),this.playbackAnalyser.fftSize=512,this.playbackAnalyser.smoothingTimeConstant=.35,this.playbackBus.connect(this.playbackAnalyser),this.playbackAnalyser.connect(this.audioContext.destination),this.playbackMeterBuffer=new Uint8Array(this.playbackAnalyser.fftSize))}stopPlaybackMeter(){this.playbackMeterFrame&&=(cancelAnimationFrame(this.playbackMeterFrame),0),this.options.onVolumeLevel?.(0,!1)}startPlaybackMeter(){if(this.playbackMeterFrame)return;let e=()=>{this.playbackNodes.length===0||!this.playbackAnalyser||!this.playbackMeterBuffer?this.stopPlaybackMeter():(this.playbackAnalyser.getByteTimeDomainData(this.playbackMeterBuffer),this.options.onVolumeLevel?.(Ce(this.playbackMeterBuffer),!1),this.playbackMeterFrame=requestAnimationFrame(e))};this.playbackMeterFrame=requestAnimationFrame(e)}async processServerEnvelope(e){if(await this.tryHandleControlEnvelope(e)||e.type!==`events`)return;let t=this.collectInboundTurn(e.events),n=t.toolCalls.filter(e=>!t.cancelledToolIds.has(e.id));for(let e of n)this.toolChain=this.toolChain.then(()=>this.options.onToolCall(e.name,e.arguments,{callId:e.id,operationId:me(e)})).catch(e=>{this.options.onError?.(K(e))});this.scheduleMediaChunks(t.mediaChunks)}enqueueServerMessage(e){this.inboundChain=this.inboundChain.then(async()=>{if(typeof e!=`string`)return;let t=ge(e);t.type===`unsupported`||t.type===`malformed`?this.options.onTurnEvent?.(t):await this.processServerEnvelope(t)}).catch(e=>{this.options.onError?.(K(e))})}async handleReadyEnvelope(e){this.options.onSessionReady?.({sessionId:e.sessionId,profile:e.profile}),this.options.voiceIngress===!1?this.becomeReady():await this.activateMicrophone()}becomeReady(){this.clearReconnect(),this.setConnectPhase(null),this.setStatus(`listening`),this.flushContext()}handleExecuteToolResultEnvelope(e){let t=this.pendingExecuteResults.get(e.operationId);t&&t.callId===e.callId&&(this.pendingExecuteResults.delete(e.operationId),e.status===`refused`?t.reject(ue(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?.(ue(e,`unavailable`)),this.setStatus(`error`)),!0)}collectInboundTurn(e){let t=Ke();for(let n of e)this.processTurnEvent(n,t);return t}processTurnEvent(e,t){switch(e.type===`provider_checkpoint`&&e.history&&(this.history=structuredClone(e.history)),(e.type===`provider_checkpoint`||e.type===`done`)&&e.providerState&&(this.providerState=e.providerState),e.type===`provider_warning`&&(this.providerState=void 0),this.options.onTurnEvent?.(e),e.type){case`evidence`:this.handleEvidenceTurnEvent(e);break;case`session`:this.handleSessionTurnEvent(e);break;case`media`:this.collectMediaTurnEvent(e,t);break;case`tool`:ze(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Re(e);t&&this.options.onTranscript?.(t.text,t.isUser,{interim:t.interim})}handleSessionTurnEvent(e){if(this.notifySessionLifecycle(e.session))return;this.serverWorking=e.session.kind===`working`;let t=Ze(this.status,this.serverWorking);t&&this.setStatus(t)}notifySessionLifecycle(e){return e.kind===`closing_soon`?(this.options.onSessionClosing?.(e.timeLeftMs),!0):e.kind===`ended`?this.providerState?(this.handleDrop(),!0):(this.sessionOver=!0,this.options.onSessionEnded?.(e),!0):!1}restingStatus(){return this.serverWorking?`working`:`listening`}collectMediaTurnEvent(e,t){e.media.data&&(this.setStatus(`speaking`),t.mediaChunks.push({data:e.media.data,mimeType:e.media.mimeType}))}handleDoneTurnEvent(e){e.interrupted&&this.cancelPlayback(),e.stop.kind!==`generation_complete`&&(this.serverWorking=!1,this.setStatus(`listening`))}scheduleMediaChunks(e){if(e.length===0)return;let t=this.audioEpoch;for(let n of e)this.audioChain=this.audioChain.then(async()=>{t===this.audioEpoch&&await this.enqueueAudioChunk(n.data,n.mimeType)}).catch(e=>{this.options.onError?.(K(e))})}executeToolOnRelay(e){let t=this.ws;if(!t||t.readyState!==WebSocket.OPEN)throw new H(`request`,`live session is not connected`);let n=_e.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new H(`request`,se(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new H(`request`,se(`session.gate_expired`));return new Promise((e,n)=>{this.pendingExecuteResults.set(r.operationId,{callId:r.callId,resolve:e,reject:n});try{t.send(G(r))}catch(e){this.pendingExecuteResults.delete(r.operationId),n(K(e))}})}async enqueueAudioChunk(e,t){if(this.audioContext)try{if(this.ensurePlaybackBus(),!this.playbackBus)return;let n=le(e),r;if(t?.includes(`wav`)){let e=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);r=await this.audioContext.decodeAudioData(e)}else{let e=Ge(n);r=this.audioContext.createBuffer(1,e.length,24e3),r.getChannelData(0).set(e)}let i=this.audioContext.createBufferSource();i.buffer=r,i.connect(this.playbackBus);let a=this.audioContext.currentTime,o=Math.max(a,this.nextPlaybackTime);i.start(o),this.nextPlaybackTime=o+r.duration,this.playbackNodes.push(i),this.startPlaybackMeter(),i.onended=()=>{let e=this.playbackNodes.indexOf(i);e!==-1&&this.playbackNodes.splice(e,1),this.playbackNodes.length===0&&(this.stopPlaybackMeter(),this.status===`speaking`&&this.setStatus(this.restingStatus()))}}catch(e){this.options.onError?.(K(e))}}cancelPlayback(){this.audioEpoch+=1,this.audioChain=Promise.resolve();for(let e of this.playbackNodes)try{e.stop(),e.disconnect()}catch{}this.playbackNodes=[],this.stopPlaybackMeter(),this.audioContext&&(this.nextPlaybackTime=this.audioContext.currentTime)}toggleMute(){return this.isMuted=!this.isMuted,this.isMuted}sendText(e){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(G({type:`text`,text:e}))}setSlots(e){JSON.stringify(e)!==JSON.stringify(this.options.slots)&&(this.options={...this.options,slots:e},this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop())}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(G({type:`context`,context:this.context})))}sendVideo(e,t=`image/jpeg`){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(G({type:`video`,data:e,mimeType:t}))}disconnect(){this.clearReconnect(),this.lostAt=void 0,this.providerState=void 0,this.teardownConnection(),this.setStatus(`disconnected`)}cleanupAudio(){if(this.cancelPlayback(),this.stopPlaybackMeter(),q(this.playbackBus),this.playbackBus=null,this.playbackAnalyser=null,this.playbackMeterBuffer=null,this.micWorklet&&=(this.micWorklet.port.onmessage=null,q(this.micWorklet),null),q(this.micSource),this.micSource=null,Ye(this.micStream),this.micStream=null,this.audioContext&&this.audioContext.state!==`closed`){try{this.audioContext.close()}catch{}this.audioContext=null,this.micWorkletModuleLoaded=!1}}},J=e(i(),1);function $e(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function et(e,t){return t.length===0?e:[...e,[...t]]}function tt(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:nt(e,t):e:t}function nt(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function rt(e){return`${String(Date.now())}-${String(e.turns.length)}`}function it(e,t,n,r,i){if(!t)return e;if(r)return n?{...e,interimUser:t}:{...e,interimAgent:t};let a=n?`user`:`agent`,o=[...e.turns],s=o.at(-1),c=n?e.interimUser:e.interimAgent;if(!i?.forceNew&&s?.role===a)o[o.length-1]={...s,text:nt(s.text,t)};else{let n=i?.forceNew?t:tt(c,t);o.push({id:rt(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function at(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function ot(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function st(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:ot(e,t.tool.callId);let n=e.at(-1)?.role===`work`;return t.type===`thought`&&!(n?t.text:t.text.trim())?-1:n?e.length-1:e.length}function ct(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!at(t))return e;let n=st(e.turns,t);if(n===-1)return e;let r=[...e.turns],i=r[n];return r[n]=i?.role===`work`?{...i,events:[...i.events,t]}:{id:rt(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function lt(e){return e.role===`work`?he(e.events,{idPrefix:e.id}):[{id:e.id,kind:e.role===`user`?`user-text`:`text`,text:e.text}]}var ut=24;function dt(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function ft(e,t){let n=e.trim();return dt(n,t.trim())>=Math.min(n.length,ut)}function pt(e){return e.filter((t,n)=>{if(t.role!==`agent`)return!0;let r=e.slice(n+1),i=r.findIndex(e=>e.role===`user`);return!(i===-1?r:r.slice(0,i)).some(e=>e.role===`agent`&&ft(t.text,e.text))})}function mt(e,{turns:t,interimUser:n,interimAgent:r}){let i=[...t];n&&i.push({id:`interim-user`,role:`user`,text:n}),r&&i.push({id:`interim-agent`,role:`agent`,text:r});let a=[...e.map((e,t)=>e.map(e=>({...e,id:`${String(t)}:${e.id}`}))),i].map(e=>pt(e).flatMap(lt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function ht({working:e,interimAgent:t}){return t!==``||e}function gt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function _t(e,t){let n=Object.keys(t??{}).sort().join(`
2
- `),r=e?.join(`
3
- `);(0,J.useEffect)(()=>{r!==void 0&&Ee(r?r.split(`
4
- `):[],n?n.split(`
5
- `):[])},[r,n])}var vt=.62,yt=400;function bt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function xt(e,t){let n=t?.facingMode??`user`;return bt(n).then(t=>{let r=document.createElement(`video`);r.srcObject=t,r.muted=!0,r.playsInline=!0,r.setAttribute(`playsinline`,``);let i=document.createElement(`canvas`),a=i.getContext(`2d`);if(!a){for(let e of t.getTracks())e.stop();throw new H(`unsupported`,`no 2d canvas for live video`)}let o=null,s=!1,c={stream:t,facing:n},l=()=>{if(s||r.videoWidth===0)return;i.width=r.videoWidth,i.height=r.videoHeight,a.drawImage(r,0,0);let t=i.toDataURL(`image/jpeg`,vt).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,yt))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await bt(e);for(let e of c.stream.getTracks())e.stop();return c={stream:t,facing:e},r.srcObject=t,await r.play(),e},stop:()=>{s=!0,o&&clearInterval(o),o=null,r.srcObject=null;for(let e of c.stream.getTracks())e.stop()}}})}function St(e){let t=(0,J.useCallback)(()=>{e.cancelGateDecision(),e.clearClient(),e.stopVideo(),e.setIsMuted(!1),e.isMutedRef.current=!1,e.setSessionActive(!1),e.setSessionPermissions([]),e.sessionPermissionsRef.current=[],e.statusRef.current=`disconnected`,e.setStatus(`disconnected`),e.setConnectPhase(null),e.setInputLevel(0),e.setOutputLevel(0)},[e]),n=(0,J.useCallback)(async()=>{e.clearFailure(),e.resetCaptions();try{let t=e.ensureClient(await e.connectionRef.current());(e.statusRef.current===`disconnected`||e.statusRef.current===`error`)&&await t.connect()}catch(t){e.reportFailure(t)}},[e]);return{teardownSession:t,startSession:n,handleSendText:(0,J.useCallback)(t=>{let n=(typeof t==`string`?t:e.textDraft).trim();n&&e.clientRef.current&&e.sessionActive&&e.textAvailable&&(e.clientRef.current.sendText(n),e.setTextDraft(``),e.setCaptions(e=>it(e,n,!0,!1,{forceNew:!0})))},[e]),handleToggleVideo:(0,J.useCallback)(async()=>{if(e.clientRef.current&&e.sessionActive&&e.videoAvailable){if(e.isVideoOn)e.stopVideo();else try{let t=await xt(t=>{e.clientRef.current?.sendVideo(t)});e.videoCaptureRef.current=t,e.setVideoPreview(t.video),e.setVideoFacingMode(t.facingMode()),e.setIsVideoOn(!0)}catch(t){e.reportFailure(t),e.stopVideo()}}},[e]),handleFlipCamera:(0,J.useCallback)(async()=>{let t=e.videoCaptureRef.current;if(t&&e.sessionActive&&e.isVideoOn)try{let n=await t.flip();e.setVideoFacingMode(n),e.setVideoPreview(t.video)}catch(t){e.reportFailure(t)}},[e]),handleToggleMic:(0,J.useCallback)(()=>{if(!e.clientRef.current||!e.sessionActive||!e.voiceAvailable)return;let t=e.clientRef.current.toggleMute();e.isMutedRef.current=t,e.setIsMuted(t)},[e]),handleRestart:(0,J.useCallback)(async()=>{t(),await n()},[n,t])}}function Ct(e){return new de(e.kind,e.error,e.message)}function Y(e){e.gateCallId===void 0&&e.clearActiveTool()}function wt(e,t){e.phase===`cancel`&&e.callId===t.gateCallId?(t.withdrawGate(),t.clearActiveTool()):e.phase===`cancel`||e.phase===`complete`?Y(t):e.phase===`error`?(t.reportFailure(Ct(e.failure)),Y(t)):t.setActiveTool(e.name)}function Tt(e,t){e.type===`done`?(t.clearInterim(),Y(t)):e.type===`tool`&&wt(e.tool,t)}function Et(e){let[t,n]=(0,J.useState)(`disconnected`),[r,i]=(0,J.useState)(null),a=(0,J.useRef)({input:0,output:0}),o=(0,J.useCallback)(e=>{let t=a.current;t.input=typeof e==`function`?e(t.input):e},[]),s=(0,J.useCallback)(e=>{let t=a.current;t.output=typeof e==`function`?e(t.output):e},[]),[c,l]=(0,J.useState)(!1),[u,d]=(0,J.useState)(!1),[p,m]=(0,J.useState)(null),[h,g]=(0,J.useState)($e),[_,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(``),[C,ee]=(0,J.useState)(!1),[w,T]=(0,J.useState)([]),[E,D]=(0,J.useState)(!1),[O,k]=(0,J.useState)(null),[A,j]=(0,J.useState)(`user`),M=(0,J.useRef)(null),N=(0,J.useRef)(h),P=(0,J.useRef)(c),F=(0,J.useRef)(w),I=(0,J.useRef)(t);return N.current=h,P.current=c,F.current=w,I.current=t,(0,J.useEffect)(()=>{C&&D(!0)},[C]),{status:t,setStatus:n,connectPhase:r,setConnectPhase:i,levelsRef:a,setInputLevel:o,setOutputLevel:s,isMuted:c,setIsMuted:l,isVideoOn:u,setIsVideoOn:d,activeTool:p,setActiveTool:m,captions:h,setCaptions:g,failure:_,reportFailure:(0,J.useCallback)(t=>{v(f(t,e))},[e]),clearFailure:(0,J.useCallback)(()=>{v(null)},[]),sessionEnded:y,reportSessionEnded:(0,J.useCallback)(e=>{b(e.message)},[]),clearSessionEnded:(0,J.useCallback)(()=>{b(null)},[]),textDraft:x,setTextDraft:S,sessionActive:C,setSessionActive:ee,sessionPermissions:w,setSessionPermissions:T,everConnected:E,videoPreview:O,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,J.useCallback)(()=>{g($e())},[]),stopVideo:(0,J.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),d(!1)},[])}}function Dt(e){let[t,n]=(0,J.useState)(null),r=(0,J.useRef)(t);r.current=t;let i=(0,J.useRef)(null),a=(0,J.useRef)(null),o=(0,J.useCallback)(e=>{i.current?.(e),i.current=null,a.current=null,n(null)},[]);return{gatePrompt:t,gatePromptRef:r,handleLiveTurnEvent:(0,J.useCallback)(t=>{e.setCaptions(e=>ct(e,t)),Tt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>gt(e))},clearActiveTool:()=>{e.setActiveTool(null)},reportFailure:e.reportFailure,setActiveTool:e.setActiveTool})},[e,o]),waitForGateDecision:(0,J.useCallback)(e=>new Promise((t,r)=>{n(e),i.current=t,a.current=r}),[]),resolveGateDecision:(0,J.useCallback)(e=>{o(e)},[o]),cancelGateDecision:(0,J.useCallback)(()=>{a.current?.(new H(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}async function Ot(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.sessionPermissions,s=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,c=await t({callId:i,operationId:a}),l=new Set;for(;c.status!==`settled`;){if(c.status===`dispatched`){if(l.has(c.grantId))return;l.add(c.grantId);let e=c.grantId,n=c.arguments,r=s?await Promise.resolve().then(()=>s(n,{callId:i,operationId:a})).catch(()=>void 0):void 0;c=await t({callId:i,operationId:a,grantId:e,...r?{output:r.output}:{unanswered:!0}});continue}let{gate:u}=c;if(u.kind===`page`){await t({callId:i,operationId:a,decision:`deny`});return}let d=await e.waitForGateDecision({callId:i,toolName:n,input:u.preparedArguments??r,gate:u});if(d===`withdrawn`)return;let f=oe({toolName:n,gate:u,sessionPermissions:o,resolution:d});if(f.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}o=f.sessionPermissions,e.setSessionPermissions(f.sessionPermissions),c=await t({callId:i,decision:`approve`,operationId:a,...f.secret===void 0?{}:{secret:f.secret}})}}function kt(e,t){t.setStatus(e),e===`listening`||e===`ready`?(t.setSessionActive(!0),t.clearFailure(),t.clearSessionEnded()):(e===`disconnected`||e===`error`)&&(t.setSessionActive(!1),t.videoCaptureRef.current&&(t.videoCaptureRef.current.stop(),t.videoCaptureRef.current=null),t.setVideoPreview(null),t.setVideoFacingMode(`user`),t.setIsVideoOn(!1))}function At(e,t,n,r){r.setCaptions(r=>it(r,e,t,n?.interim))}async function jt(e,t,n,r,i){r.setActiveTool(e),r.clearFailure();let a=i.current;if(!a)r.reportFailure(new H(`request`,`live tool call with no session client`));else try{await Ot({pageTools:r.pageTools,executeToolOnRelay:e=>a.executeToolOnRelay(e),name:e,toolArgs:t,callId:n.callId,operationId:n.operationId,sessionPermissions:r.sessionPermissionsRef.current,setSessionPermissions:e=>{r.sessionPermissionsRef.current=e,r.setSessionPermissions(e)},waitForGateDecision:r.waitForGateDecision})}catch(e){r.reportFailure(e)}finally{r.gatePromptRef.current||r.setActiveTool(null)}}function Mt(e){let t=(0,J.useRef)(null),n=(0,J.useRef)(e);return n.current=e,{clientRef:t,ensureClient:(0,J.useCallback)(e=>{if(t.current)return t.current;let r=n.current,i=new Qe({...e,slots:r.slots,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{kt(e,n.current)},onTranscript:(e,t,r)=>{At(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):n.current.handleLiveTurnEvent(e))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},onToolCall:(e,r,i)=>jt(e,r,i,n.current,t)});return t.current=i,i},[]),clearClient:(0,J.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function Nt(e,t,n,r){let[i,a]=(0,J.useState)(!1),[o,s]=(0,J.useState)(!1),c=(0,J.useRef)(!1),l=(0,J.useCallback)(t=>{c.current=t.video&&r,a(!0),s(!1),e.startSession()},[e,r]);(0,J.useEffect)(()=>{n&&c.current&&(c.current=!1,e.handleToggleVideo())},[e,n]);let u=(0,J.useCallback)(()=>{c.current=!1,e.teardownSession(),s(!0)},[e]),[d,f]=(0,J.useState)([]),p=(0,J.useCallback)(async()=>{let n=t.current.turns;f(e=>et(e,n)),s(!1),await e.handleRestart()},[e,t]),m=(0,J.useRef)(e.teardownSession);return m.current=e.teardownSession,(0,J.useEffect)(()=>()=>{m.current()},[]),{callStarted:i,ended:o,pastCalls:d,startCall:l,handleEnd:u,handleRestart:p}}function Pt(e,t,n={}){let r=Et(e.labels),i=Dt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,J.useRef)(t);a.current=t;let o=U(e.live.ingress,`audio`),s=U(e.live.ingress,`video`),c=U(e.live.ingress,`text`),l=(0,J.useMemo)(()=>Ie({status:r.status,connectPhase:r.connectPhase,toolName:r.activeTool,isMuted:r.isMuted,voiceEnabled:o}),[r.activeTool,r.connectPhase,r.isMuted,r.status,o]),u=(0,J.useMemo)(p,[]),{clientRef:d,ensureClient:f,clearClient:m}=Mt({slots:n.slots,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),h=St({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:m,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:g,ended:_,pastCalls:v,startCall:y,handleEnd:b,handleRestart:x}=Nt(h,r.captionsRef,r.sessionActive,s),S=JSON.stringify(n.context);(0,J.useEffect)(()=>{d.current?.setContext(S===void 0?void 0:JSON.parse(S))},[d,S]);let C=JSON.stringify(n.slots);return(0,J.useEffect)(()=>{d.current?.setSlots(C===void 0?void 0:JSON.parse(C))},[d,C]),_t(e.tools.page,n.pageTools),{handle:e.identity.handle,traces:u,callStarted:g,pastCalls:v,captions:r.captions,failure:r.failure,sessionEnded:r.sessionEnded,levelsRef:r.levelsRef,isMuted:r.isMuted,isVideoOn:r.isVideoOn,sessionActive:r.sessionActive,liveState:l,activeTool:r.activeTool,status:r.status,textAvailable:c,textDraft:r.textDraft,toolActive:r.activeTool!==null||i.gatePrompt!==null,videoAvailable:s,videoFacingMode:r.videoFacingMode,videoPreview:r.videoPreview,voiceAvailable:o,canRestart:!r.sessionActive&&r.status!==`connecting`&&(r.everConnected||_||r.failure!==null),gatePrompt:i.gatePrompt,setTextDraft:r.setTextDraft,handleEnd:b,startCall:y,handleRestart:x,handleSendText:h.handleSendText,handleToggleMic:h.handleToggleMic,handleFlipCamera:h.handleFlipCamera,handleToggleVideo:h.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var X=t(),Ft={0:`--spacing-0`,.5:`--spacing-0-5`,1:`--spacing-1`,1.5:`--spacing-1-5`,2:`--spacing-2`,3:`--spacing-3`,4:`--spacing-4`,5:`--spacing-5`,6:`--spacing-6`,8:`--spacing-8`,10:`--spacing-10`},Z={baseFlex:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x1qughib`,$$css:!0},baseGrid:{k1xSpc:`xrvj5dj`,kumcoG:`x134kloy`,kGNEyG:`x6s0dn4`,$$css:!0},vertical:{kXwgrk:`xdt5ytf`,kGNEyG:`x1qjc9v5`,$$css:!0},startSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,$$css:!0},centerSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`xl56j7k`,k7Eaqz:`xeuugli`,$$css:!0},endSlot:{k1xSpc:`x78zum5`,kGNEyG:`x6s0dn4`,kjj79g:`x13a6bvl`,$$css:!0},startOnly:{kUk6DE:`x845mor`,$$css:!0},endOnly:{keTefX:`xvc5jky`,$$css:!0}},It={base:{kAzted:`x1gdqauq`,$$css:!0}},Q={gap:e=>[{kOIVth:e==null?e:`x1pidvrl`,$$css:!0},{"--x-gap":(e=>typeof e==`number`?e+`px`:e??void 0)(e)}],tabIndicatorBottom:e=>[{"--_tab-indicator-bottom":e==null?e:`xbrl7fg`,$$css:!0},{"--x---_tab-indicator-bottom":e??void 0}]},Lt={sm:2,md:2,lg:2},Rt={sm:a[`--spacing-2`],md:a[`--spacing-2`],lg:a[`--spacing-2`]},$={sm:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,md:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`,lg:`calc(var(--container-padding-inline-start, ${a[`--spacing-4`]}) - ${a[`--spacing-2`]})`};function zt({startContent:e,centerContent:t,endContent:i,label:s,size:c=`md`,gap:l=1,orientation:u=`horizontal`,variant:d=`transparent`,dividers:f,xstyle:p,className:m,style:h,ref:g,onKeyDown:_,onFocus:b,onBlur:S,role:C,"aria-label":w,"aria-orientation":T,...E}){let D=t!=null,O=e!=null,k=i!=null,A=f?.includes(`bottom`)??!1,j=a[Ft[l]],{listRef:M,handleKeyDown:N,handleFocus:P}=y({itemSelector:`button, input, [tabindex]`,boundarySelector:`[role="toolbar"], [popover]`,orientation:u,hasRovingTabIndex:!0,hasCaretGuard:!0}),{hintElement:F,onKeyDown:I,onFocus:L,onBlur:R}=o({orientation:u}),z=(0,J.useCallback)(e=>{_?.(e),!e.defaultPrevented&&(I(e),N(e))},[_,I,N]),B=(0,J.useCallback)(e=>{b?.(e),!e.defaultPrevented&&(L(e),P(e))},[b,L,P]),te=(0,J.useCallback)(e=>{S?.(e),!e.defaultPrevented&&R(e)},[S,R]);return(0,X.jsx)(ee,{value:c,children:(0,X.jsx)(ye,{ref:g,variant:d,paddingBlock:Lt[c],dividers:f,xstyle:p,className:m,style:h,children:(0,X.jsxs)(`div`,{ref:M,role:`toolbar`,"aria-label":s,"aria-orientation":u,onKeyDown:z,onFocus:B,onBlur:te,...v(r(`toolbar`,{size:c}),n(D?Z.baseGrid:Z.baseFlex,u===`vertical`&&Z.vertical,It.base,Q.gap(j),A&&Q.tabIndicatorBottom(`calc(-1 * (${Rt[c]} + 1px))`))),...E,children:[D?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{...n(Z.startSlot,x.inset($[c]),Q.gap(j)),children:e}),(0,X.jsx)(`div`,{...n(Z.centerSlot,Q.gap(j)),children:t}),(0,X.jsx)(`div`,{...n(Z.endSlot,x.inset($[c]),Q.gap(j)),children:i})]}):(0,X.jsxs)(X.Fragment,{children:[O&&(0,X.jsx)(`div`,{...n(Z.startSlot,!k&&Z.startOnly,x.inset($[c]),Q.gap(j)),children:e}),k&&(0,X.jsx)(`div`,{...n(Z.endSlot,!O&&Z.endOnly,x.inset($[c]),Q.gap(j)),children:i})]}),F]})})})}zt.displayName=`Toolbar`;function Bt(e){return(0,X.jsx)(M,{children:(0,X.jsx)(Vt,{...e})})}function Vt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o,showComposer:s=!0,leading:c}){let u=j(),f=u(`@theorem.agent.handle`,{handle:e}),{blocks:p,callStarts:m}=mt(n,t),h=u(`@theorem.live.new_session`),g=Object.fromEntries(m.map(e=>[e,h])),_=s?(0,X.jsx)(be,{handle:e,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o}):null;return(0,X.jsxs)(l,{height:`100%`,children:[c,(0,X.jsx)(d,{size:`fill`,children:p.length>0?(0,X.jsx)(D,{label:u(`@theorem.panel.captions.name`),children:(0,X.jsx)(xe,{blocks:p,dividers:g,handle:f,streaming:ht(t)})}):(0,X.jsx)(l,{height:`100%`,vAlign:`center`,padding:4,children:(0,X.jsx)(ve,{icon:(0,X.jsx)(b,{icon:Ne,size:`lg`,color:`secondary`}),title:u(`@theorem.panel.captions.empty.title`),description:u(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),_]})}var Ht=class{readyState=0;binaryType=`arraybuffer`;onopen=null;onmessage=null;onclose=null;onerror=null;outbound=new EventTarget;closeSession;queued=[];listening=!1;constructor(e,t,n){queueMicrotask(()=>{this.open(e,t,n)})}send(e){if(this.readyState!==1)throw new H(`network`,`Live connection is closed`);this.listening?this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e})):this.queued.push(e)}close(){this.readyState!==3&&(this.readyState=3,this.queued=[],this.outbound.dispatchEvent(new Event(`close`)),this.closeSession?.(),this.emit(`onclose`,new CloseEvent(`close`)))}emit(e,t){let n=this[e];n?.(t)}async open(e,t,n){if(this.readyState===3)return;this.readyState=1,this.emit(`onopen`,new Event(`open`));let r;try{let i=await _(),a=n?.(i);r=i.studioTraces.route(e=>this.receive({type:`trace`,record:e}));let{scope:o,profile:s}=await i.studioScope(e.profile,e.customTools,e.structured,t);if(!t.providers?.vault)throw new H(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new H(`request`,`A live call must open with its open message`);let l=await o.runSession({...await(a?(await a.boundary).prepareLiveOpen(i.parseLiveOpenMessage(c)):Promise.resolve(i.liveSessionOpen(i.parseLiveOpenMessage(c)))),profile:s.id,metadata:r.metadata,signal:t.signal},{execution:t.execution??a?.execution,pageExecution:t.pageExecution??a?.pageExecution,vault:t.providers.vault,fetch:t.providers.fetch,wait:t.providers.wait,openWebSocket:t.providers.openWebSocket});if(this.closeSession=()=>l.close(`client disconnected`),this.readyState!==1){await this.closeSession(),r.close();return}await this.attach(i.attachStudioLiveSession,l,s.id,r,s.labels,a?{pageResult:a.pageResult,beforeEvent:async e=>{(e.type===`done`||e.type===`provider_checkpoint`)&&e.providerState&&await(await a.boundary).recordCheckpoint(e.providerState)}}:{})}catch(t){r?.close(),this.receive({type:`error`,...fe(t,e.profile.labels,pe)}),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:pe});this.closeSession=void 0,this.listening=!0;for(let e of this.queued.splice(0))this.outbound.dispatchEvent(new MessageEvent(`message`,{data:e}));await o}receive(e){this.readyState===1&&this.emit(`onmessage`,new MessageEvent(`message`,{data:JSON.stringify(e)}))}};function Ut(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new Ht(e,t,r)}}var Wt=720,Gt=320;function Kt({theme:e,mode:t,labels:n,...r}){return(0,X.jsx)(g,{theme:e,mode:t,children:(0,X.jsx)(M,{labels:n,children:(0,X.jsx)(qt,{...r})})})}function qt({iface:e,connection:t,trace:n,slots:r,context:i,pageTools:a}){let o=j(),u=Pt(e,t,{slots:r,context:i,pageTools:a}),d=(0,J.useRef)(null),f=F(e,u.traces,n),p=E(d,!0),m={name:o(`@theorem.panel.captions.name`),show:o(`@theorem.panel.captions.show`),hide:o(`@theorem.panel.captions.hide`),resize:o(`@theorem.panel.captions.resize`)},h=(0,X.jsx)(T,{labels:m,icon:(0,X.jsx)(b,{icon:Se}),panelId:p.id,open:p.open,onToggle:p.toggle});return u.callStarted?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(w,{children:f.toggle}),content:(0,X.jsx)(s,{padding:0,children:(0,X.jsx)(c,{height:`fill`,end:(0,X.jsx)(O,{id:p.id,labels:m,resizable:p.resizable,open:p.open,children:(0,X.jsx)(Qt,{model:u})}),content:(0,X.jsx)(s,{padding:0,children:(0,X.jsx)(l,{height:`100%`,paddingInline:3,paddingBlockEnd:4,children:(0,X.jsx)(Yt,{model:u,captionsToggle:h})})})})})})}),(0,X.jsx)(rn,{prompt:u.gatePrompt,agent:o(`@theorem.agent.handle`,{handle:u.handle}),onResolve:u.resolveGateDecision})]}):(0,X.jsx)(I,{inspector:f,children:(0,X.jsx)(c,{ref:d,height:`fill`,header:(0,X.jsx)(w,{children:f.toggle}),content:(0,X.jsx)(s,{padding:0,children:(0,X.jsx)(Jt,{model:u})})})})}function Jt({model:e}){let t=j();return(0,X.jsx)(l,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,X.jsx)(R,{axis:`horizontal`,width:`100%`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:De,gap:8,children:[(0,X.jsxs)(l,{gap:1,children:[(0,X.jsx)(k,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(k,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,X.jsxs)(u,{gap:2,wrap:`wrap`,children:[(0,X.jsx)(S,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:Me}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,X.jsx)(S,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,X.jsx)(b,{icon:Fe}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Yt({model:e,captionsToggle:t}){let n=j(),r=Xt();return(0,X.jsx)(l,{ref:r,height:`100%`,hAlign:`center`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:Wt,height:`100%`,gap:3,children:[(0,X.jsxs)(l,{gap:.5,children:[(0,X.jsx)(k,{type:`label`,color:`secondary`,children:n(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(k,{size:`sm`,color:`secondary`,children:A(n,e.liveState,e.activeTool)})]}),e.failure?(0,X.jsx)(L,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,X.jsx)(L,{status:`info`,role:`status`,title:e.sessionEnded}):null,(0,X.jsx)(d,{size:`fill`,children:(0,X.jsx)(l,{height:`100%`,vAlign:`end`,children:(0,X.jsx)(l,{width:`100%`,height:Gt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,X.jsx)(B,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,X.jsx)(Zt,{model:e,captionsToggle:t})]})})}function Xt(){let e=(0,J.useRef)(null);return(0,J.useLayoutEffect)(()=>{let t=e.current;if(!t||globalThis.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;let n=getComputedStyle(t),r=Number.parseFloat(n.getPropertyValue(`--duration-medium`))||410;t.animate([{opacity:0,transform:`translateY(8px)`},{opacity:1,transform:`none`}],{duration:r,easing:n.getPropertyValue(`--ease-standard`).trim()||`ease-out`})},[]),e}function Zt({model:e,captionsToggle:t}){let n=j(),r=!e.sessionActive,i=[];return e.voiceAvailable&&i.push((0,X.jsx)(we,{label:n(`@theorem.live.microphone`),tooltip:n(e.isMuted?`@theorem.live.unmute`:`@theorem.live.mute`),isIconOnly:!0,isPressed:!e.isMuted,isDisabled:r,icon:(0,X.jsx)(b,{icon:m}),pressedIcon:(0,X.jsx)(b,{icon:Ae}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&(i.push((0,X.jsx)(we,{label:n(`@theorem.live.camera`),tooltip:n(e.isVideoOn?`@theorem.live.camera_off`:`@theorem.live.camera_on`),isIconOnly:!0,isPressed:e.isVideoOn,isDisabled:r,icon:(0,X.jsx)(b,{icon:Fe}),pressedIcon:(0,X.jsx)(b,{icon:Pe}),onPressedChange:()=>{e.handleToggleVideo()}},`video`)),e.isVideoOn&&i.push((0,X.jsx)(C,{label:n(`@theorem.live.flip_camera`),tooltip:n(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:r,icon:(0,X.jsx)(b,{icon:ke}),onClick:()=>{e.handleFlipCamera()}},`flip`))),i.push((0,X.jsx)(J.Fragment,{children:t},`captions`),e.canRestart?(0,X.jsx)(C,{label:n(`@theorem.live.start_call`),tooltip:n(`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(b,{icon:Me}),onClick:()=>{e.handleRestart()}},`call`):(0,X.jsx)(C,{label:n(`@theorem.live.end_call`),tooltip:n(`@theorem.live.end_call`),variant:`destructive`,isDisabled:r,icon:(0,X.jsx)(b,{icon:je}),onClick:e.handleEnd},`call`)),(0,X.jsx)(zt,{label:n(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,X.jsx)(u,{gap:2,vAlign:`center`,children:i})})}function Qt({model:e}){return(0,X.jsx)(Bt,{handle:e.handle,captions:e.captions,pastCalls:e.pastCalls,draftText:e.textDraft,onDraftTextChange:e.setTextDraft,onSubmit:e.handleSendText,isDisabled:!e.sessionActive,showComposer:e.textAvailable,leading:e.videoPreview?(0,X.jsx)($t,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function $t({video:e,facingMode:t}){let n=j(),r=(0,J.useRef)(null);return(0,J.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,J.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,X.jsx)(te,{ratio:4/3,fit:`cover`,children:(0,X.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var en=4,tn=432,nn={background:`transparent`,boxShadow:`none`};function rn({prompt:e,agent:t,onResolve:n}){return(0,X.jsx)(N,{isOpen:e!==null,purpose:`required`,width:tn,padding:en,style:nn,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,X.jsx)(re,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,X.jsx)(ne,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function an({runtime:e,...t}){let{payload:n}=t;return(0,X.jsx)(sn,{...t,connect:()=>e?Ut(n,e):z(n)})}function on({endpoint:e,...t}){return(0,X.jsx)(sn,{...t,connect:()=>({createSocket:()=>new WebSocket(e.replace(/^http/,`ws`))})})}function sn({payload:e,note:t,connect:n,trace:r,slots:i,context:a}){let o=(0,J.useMemo)(()=>h(e),[e]),s=(0,J.useMemo)(()=>ae(e),[e]);return o.type===`live`?(0,X.jsx)(Kt,{labels:ie,iface:o,connection:()=>(t(),n()),trace:r,slots:i,context:a,pageTools:s}):null}export{on as ProjectLive,an as StudioLive};