@theoremjs/studio 0.3.4-next.715.geef22fd → 0.3.4-next.721.g7ff150a

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 (58) hide show
  1. package/browser-execution.d.ts +3 -2
  2. package/browser-execution.js +2 -0
  3. package/browser-live.js +2 -1
  4. package/browser-transport.js +1 -0
  5. package/package.json +4 -4
  6. package/page/assets/Banner-CvzDCsXL.js +3 -0
  7. package/page/assets/{ConsoleFrame-dOTqIkpb.js → ConsoleFrame-DwVyTmlI.js} +1 -1
  8. package/page/assets/{MenuBottomSheet-DeuZCVb-.js → MenuBottomSheet-DfwpdQHV.js} +1 -1
  9. package/page/assets/{SchemaFields-DeuNDrvj.js → SchemaFields-DDqEu_Dl.js} +1 -1
  10. package/page/assets/{ToolResultCharts-B-pokquL.js → ToolResultCharts-DgVbZ6tY.js} +1 -1
  11. package/page/assets/{TraceInspector-CvJ0wx9n.js → TraceInspector-D0_MVLtt.js} +1 -1
  12. package/page/assets/{TraceOverview-cIjJwpvK.js → TraceOverview-DKnXuaLk.js} +1 -1
  13. package/page/assets/{_virtual_studio-type-sources-BxnDf9BC.js → _virtual_studio-type-sources-BSY0b1_W.js} +65 -115
  14. package/page/assets/browser-connection-DMLe-0pv.js +3 -0
  15. package/page/assets/browser-engine-Daccda1E.js +13 -0
  16. package/page/assets/{browser-transport-DKhZ4zo1.js → browser-transport-Ddqv2L5-.js} +3 -3
  17. package/page/assets/{crypto-BnoW7FFO.js → crypto-DjhcOJmp.js} +1 -1
  18. package/page/assets/{encode-files-DoLGXgup.js → encode-files-BF1rsZES.js} +1 -1
  19. package/page/assets/{export-agent-CO4lAMum.js → export-agent-CDiThjyY.js} +1 -1
  20. package/page/assets/{guardrail-tester-Slctc2oI.js → guardrail-tester-BjJ6KSvt.js} +1 -1
  21. package/page/assets/index-Cvl7QJ2f.js +149 -0
  22. package/page/assets/live-messages-eYYz6aFz.js +1 -0
  23. package/page/assets/reader-DAdKx3ZF.js +5 -0
  24. package/page/assets/{shaped-data-7q5Be8sp.js → shaped-data-BRffby3g.js} +1 -1
  25. package/page/assets/{stub--LOYiyQO.js → stub-4NoUUWes.js} +1 -1
  26. package/page/assets/{studio-code-pane-CuccT4Ur.js → studio-code-pane-OXpOLYem.js} +3 -3
  27. package/page/assets/{studio-console-DwxLzV9_.js → studio-console-DdjCZJRm.js} +1 -1
  28. package/page/assets/{studio-decision-w6OjVUM3.js → studio-decision-Dd4-ZPqy.js} +1 -1
  29. package/page/assets/{studio-embedding-CxFoTvOd.js → studio-embedding-BCfUGzri.js} +1 -1
  30. package/page/assets/{studio-host-console-BhQSkUhA.js → studio-host-console-CwErqojz.js} +2 -2
  31. package/page/assets/{studio-labels-q6eBFSru.js → studio-labels-BZFUS19x.js} +1 -1
  32. package/page/assets/studio-live-ChYgN-57.js +5 -0
  33. package/page/assets/{studio-map-DlkGoGam.js → studio-map-CKgv43yP.js} +1 -1
  34. package/page/assets/{studio-trace-replay-Ccv4ToIz.js → studio-trace-replay-vOG3xvRR.js} +2 -2
  35. package/page/assets/{studio-type-checker-Dm2eit0p.js → studio-type-checker-BO-lN_65.js} +1 -1
  36. package/page/assets/{tool-schema-6RWBAqGO.js → tool-schema-C7lMQU0w.js} +7 -7
  37. package/page/assets/{trace-record-Dm2jEhUR.js → trace-record-Doo6lYDI.js} +1 -1
  38. package/page/assets/tree-BpAzPK_j.js +3 -0
  39. package/page/assets/{turn-client-OLK12Fyi.js → turn-client-CMgd-m7p.js} +2 -2
  40. package/page/assets/{use-one-call-CLndFp2X.js → use-one-call-B_8i95fw.js} +1 -1
  41. package/page/assets/{use-second-ticker-D6JSf9B3.js → use-second-ticker-Bx4tqkhi.js} +1 -1
  42. package/page/assets/{workspace-DSAX72vF.js → workspace-CUvoWPwb.js} +1 -1
  43. package/page/index.html +15 -15
  44. package/replay.js +1 -0
  45. package/runtime-scope.d.ts +10 -1
  46. package/runtime-scope.js +7 -0
  47. package/runtime.js +3 -0
  48. package/server/handler.js +2 -1
  49. package/server/live.js +5 -1
  50. package/ui/profile-editor.js +34 -4
  51. package/page/assets/Banner-CrhjYjDy.js +0 -3
  52. package/page/assets/browser-connection-CuWeoI9s.js +0 -3
  53. package/page/assets/browser-engine-C3SeJyrA.js +0 -13
  54. package/page/assets/index-CAK9cdCh.js +0 -149
  55. package/page/assets/live-messages-M0vS3YB0.js +0 -1
  56. package/page/assets/reader-747-Cvu8.js +0 -5
  57. package/page/assets/studio-live-D5NjMEky.js +0 -5
  58. package/page/assets/tree-DcCW259J.js +0 -3
@@ -1 +0,0 @@
1
- import{C as e,E as t,O as n,b as r,c as i,d as a,h as o,v as s,x as c}from"./schemas-D7cgkv3L.js";import{Ln as l,Wn as u,Zn as d,qn as f}from"./tool-schema-6RWBAqGO.js";import{C as p,M as m,O as h,j as g}from"./reader-747-Cvu8.js";import{n as _}from"./trace-schema--4IGmLeE.js";import{w as v}from"./turn-client-OLK12Fyi.js";var y=c({type:s(`open`),history:a(f).optional(),slots:e(t(),t()).optional(),context:n().optional(),stated:h.optional(),resume:c({providerState:d,awayMs:r().nonnegative()}).optional(),host:e(t(),n()).optional()}),b=o(`type`,[c({type:s(`audio`),data:t()}),c({type:s(`video`),data:t(),mimeType:t()}),c({type:s(`text`),text:t()}),c({type:s(`context`),context:n()}),c({type:s(`executeTool`),callId:t().min(1),operationId:t().min(1).max(256),decision:i(v).optional(),input:n().optional(),secret:t().optional(),output:n().optional(),grantId:t().min(1).optional(),unanswered:s(!0).optional()})]),x={ready:c({type:s(`ready`),profile:t().optional(),sessionId:t().optional()}),events:c({type:s(`events`),events:a(n())}),trace:c({type:s(`trace`),record:_}),error:c({type:s(`error`)}).and(p),executeToolResult:o(`status`,[c({type:s(`executeToolResult`),callId:t().min(1),operationId:t().min(1).max(256),status:s(`dispatched`),grantId:t().min(1),arguments:e(t(),n())}),c({type:s(`executeToolResult`),callId:t(),status:s(`settled`),operationId:t().min(1).max(256)}),c({type:s(`executeToolResult`),callId:t(),status:s(`gated`),operationId:t().min(1).max(256),gate:u}),c({type:s(`executeToolResult`),callId:t(),status:s(`refused`),operationId:t().min(1).max(256),body:p})])};function S(e){let t=g(x,e);return t.type===`events`?{type:`events`,events:t.events.map(e=>m(l,e))}:t}export{y as n,S as r,b as t};
@@ -1,5 +0,0 @@
1
- import{t as e}from"./preload-helper-DpV6A1kQ.js";import{C as t,D as n,E as r,O as i,S as a,T as o,b as s,c,d as l,g as u,h as d,l as f,m as p,o as m,p as h,pt as g,s as _,t as v,u as y,v as b,x}from"./schemas-D7cgkv3L.js";import{$n as S,Cn as C,Hn as ee,Kn as w,Ln as T,Qt as E,Rn as D,Sn as O,St as te,U as ne,Wt as re,X as ie,Yn as ae,Zt as oe,_n as se,_t as ce,ar as le,bn as k,er as A,ir as ue,mt as de,nr as fe,qn as pe,rr as me,s as he,tr as ge,un as _e,vn as ve,xn as ye,zn as be}from"./tool-schema-6RWBAqGO.js";import{c as j}from"./host-patterns-F-KZIzkF.js";import{$ as xe,Ar as Se,Bt as Ce,Ct as we,Dt as Te,En as Ee,Er as De,F as Oe,Fr as ke,G as Ae,Gt as je,Ht as Me,I as Ne,It as Pe,Kt as Fe,L as Ie,Lr as M,Lt as Le,Mr as Re,Mt as ze,N as Be,Nt as Ve,P as He,Pn as Ue,Pr as We,Pt as Ge,Qt as Ke,R as qe,Rt as Je,Sr as Ye,Tr as Xe,Tt as Ze,Ut as Qe,V as $e,Vt as et,Wn as tt,Wt as nt,Z as rt,_n as it,at,br as ot,cn as st,cr as ct,dt as lt,en as ut,gn as dt,gr as ft,ht as pt,it as mt,j as ht,jr as gt,ln as _t,lr as vt,mn as yt,nn as bt,nr as xt,nt as St,pt as Ct,rr as wt,rt as Tt,sn as Et,tn as Dt,tt as Ot,vn as kt,xn as At,xt as jt,zn as Mt,zt as Nt}from"./shaped-data-7q5Be8sp.js";import{$ as Pt,B as Ft,F as It,G as Lt,H as Rt,I as zt,K as Bt,O as Vt,P as Ht,Q as Ut,Y as Wt,_ as Gt,b as Kt,et as qt,f as Jt,h as Yt,k as Xt,l as Zt,q as Qt,u as $t,y as en,z as tn}from"./browser-connection-CuWeoI9s.js";import{a as nn}from"./live-ingress-OuSlQ6q7.js";import{n as rn,t as an}from"./trace-schema--4IGmLeE.js";import{n as on}from"./stub--LOYiyQO.js";function sn(e){return{type:`guardrail`,guardrail:e}}function cn(e,t,n,r=`redact`,i){if(n.length!==0)return sn({stage:e,trust:t,action:r,hits:n,...i?{provenance:i}:{}})}function ln(e,t){return e.type===`guardrail`?{...e,guardrail:wt(e.guardrail,t)}:e}var un=65536;function N(e){let t=e.classStarts.length,n=new Uint16Array(un);for(let r=0;r<t;r++)n.fill(r,e.classStarts[r],e.classStarts[r+1]??un);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 dn,P,fn;async function pn(){if(dn)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}},[]);dn={forward:t,reversed:n}}function mn(){if(!dn)throw Error(`A stream was opened before loadEgressAutomata() finished.`);return dn}var F;function hn(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 gn(e){if(!F){F=new Map;for(let e=0;e<un;e++){let t=hn(e),n=F.get(t);n?n.push(e):F.set(t,[e])}}return F.get(hn(e))??[e]}function _n(e){let t=[0];for(let n of e)t.at(-1)!==n&&t.push(n),n+1<un&&t.push(n+1);return t}var vn=new Map;function yn(e){let t=vn.get(e);if(t)return t;let n=Array.from({length:e.length},(t,n)=>gn(e.charCodeAt(n))),r=_n([...new Set(n.flat())].sort((e,t)=>e-t)),i=e=>r.indexOf(e),a=N({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 vn.set(e,a),a}function bn(e){let t=JSON.stringify(e),n=vn.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=_n(r),a=r.map(e=>[i.indexOf(e)]),o=[],s=N({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 vn.set(t,s),s}function xn(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 I(e,t){let n=Cn(e);return t>=n?e.fresh.charCodeAt(t-n):e.text.charCodeAt(t)}function wn(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 Tn(e){let t={text:``,fresh:``,rawAt:e=>e,update(){t.text=e.text,t.fresh=e.fresh}};return t}function En(e,t){let n={text:``,fresh:``,rawAt:e.rawAt,update(){n.fresh=``,Sn(n,t(wn(e,n.text.length)))}};return n}var Dn=/\w/,On=Math.max(...Je.map(e=>e.length));function kn(e){return e.length<=On+1&&/^[A-Za-z]*$/.test(e)}function An(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(I(e,t)),o=Dn.test(i);o&&!r&&(n=``),r=o,o?n===void 0?a(i,t,1):n+=i:(n!==void 0&&a(Me(n),t-n.length,n.length),n=void 0,a(i,t,1))}n!==void 0&&!kn(n)&&(a(n,t-n.length,n.length),n=void 0)}};return o}function jn(e){let t={text:``,fresh:``,from:[],rawAt:n=>n<t.from.length?t.from[n]:e(),update(){}};return t}function L(e,t,n){Sn(e,t);for(let r=0;r<t.length;r++)e.from.push(n)}var Mn=55296,Nn=56319,Pn=/[A-Za-z]/,Fn=56320,In=57343;function Ln(e){let t=0,n=``,r=[],i=``,a=[],o=!1,s=-1,c=jn(()=>Math.min(t,r[0]??t,a[0]??t,s<0?t:s));function l(e,t){s>=0&&(Pn.test(e)||L(c,`\\`,s),s=-1),e===`\\`?s=t:L(c,e,t)}function u(e,t){if(Qe(e)&&(o||i)){i+=e;for(let n=0;n<e.length;n++)a.push(t)}else{if(i){if(!Pn.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=Pn.test(e)&&e.length===1}}function d(){let e=0;for(;e<n.length;){let t=n.charCodeAt(e),i=t>=Mn&&t<=Nn;if(i&&e+1>=n.length)break;let a=n.charCodeAt(e+1),o=i&&a>=Fn&&a<=In?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=I(e,t),o=a>=Mn&&a<=Nn;if(o&&t+1>=i)break;let s=I(e,t+1),c=o&&s>=Fn&&s<=In?2:1,l=nt(wn(e,t,t+c));n+=l;for(let e=0;e<l.length;e++)r.push(t);t+=c}d()},c}var Rn=/[0-9A-Fa-f]/;function zn(e){let t=0,n=-1,r=jn(()=>n<0?t:n);r.update=()=>{r.fresh=``;let a=e.text.length;for(;t<a;){let a=String.fromCharCode(I(e,t));if(n<0){a===`%`?n=t:(L(r,a,t),t++);continue}let o=(t-n)%3;if(o===0?a===`%`:Rn.test(a))t++;else{i(t-o);for(let n=t-o;n<t;n++)L(r,String.fromCharCode(I(e,n)),n)}}};function i(t){t>n&&L(r,Nt(wn(e,n,t)),n),n=-1}return r}var Bn=new Set([`injection`,`base64`,`hex`,`spaced`,`pipe`]),Vn=new Map(Le.map(({pattern:e,hit:t})=>[e,t])),Hn=new Map(St.flatMap(({pattern:e,hit:t})=>t?[[e,t]]:[]));function R(e){return{rule:ct(e),severity:`high`,detector:e}}var Un=R(`injection`),Wn=R(`marker_leak`),Gn=R(`tool_leak`);function Kn({kind:e,group:t}){if(Bn.has(e))return Un;switch(e){case`sensitive`:case`card`:return t===void 0?void 0:R(t);case`boundary`:return Wn;case`image`:return R(`ungiven_images`);default:return R(`ungiven_links`)}}function qn(e,t,n){if(e===`card`)return{hit:Tt};if(e===`image`||e===`link`){let r=(e===`image`?mt:at).indexOf(t),i=n[e][r];return`find`in i?{find:i.find}:{hit:i.test}}let r=Vn.get(t)??Hn.get(t);return r?{hit:r}:{}}function Jn(e,{given:t,allow:n,skipImages:r}){let i=e=>({...e,...t?{given:t}:{}}),a={image:lt(i(n?.ungiven_images)),link:Ct(i(n?.ungiven_links),r??e.includes(`ungiven_images`))},o=[];return xe.forEach((t,n)=>{let r=Kn(t);r?.detector&&e.includes(r.detector)&&o.push({...r,id:n,regex:Fe(t.pattern),...qn(t.kind,t.pattern,a)})}),o}function Yn(){let e=[];return xe.forEach(({kind:t,pattern:n},r)=>{if(t!==`injection`)return;let i=Vn.get(n);e.push({...Un,id:r,regex:Fe(n),...i?{hit:i}:{}})}),e}function Xn(){return je.map((e,t)=>({...Un,id:t,regex:new RegExp(e.source,e.flags)}))}function Zn(e,t,n){let r=xn(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),C=[...new Set(S)].filter(e=>e>=0),ee=n.flatMap((e,t)=>S[t]<0?[]:[t]),w=new Int32Array(t.has.length).fill(-1);function T(){let{text:n,fresh:h}=e,g=Cn(e),{classOf:_,has:v,edges:ee,final:T,pattern:E}=t;for(;p<n.length;p++){let e=_[p>=g?h.charCodeAt(p-g):n.charCodeAt(p)];f++;let t=0,D=(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++,T[e]&&(m[i[E[e]]]=1)};for(let t=0;t<l;t++){let n=ee[a[t]],r=o[t];for(let t=0;t<n.length;t+=2)v[n[t+1]][e]&&D(n[t],r)}let O=r[e];for(let e=0;e<O.length;e++){let t=O[e],n=i[E[t]],r=S[n],a=r<0?-1:w[r],o=a<0?p:a;D(t,o),y[n]&&(x[n]=p,b[n]<0&&(b[n]=o))}for(let t of C)v[t][e]?w[t]<0&&(w[t]=p):w[t]=-1;[a,s]=[s,a],[o,c]=[c,o],l=t}}function E(){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 ee){let t=w[S[e]];t<0||(t<_[e]&&(_[e]=t),t<r&&(r=t))}return r}function D(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 O={text:``,lower:``},te=()=>(O.text!==e.text&&(O={text:e.text,lower:e.text.toLowerCase()}),O.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,te)))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 re(){for(let e=0;e<n.length;e++){let t=_[e];if(t<=g[e])continue;let r=n[e].find?D(e,t):ne(e,t);if(r)return r}}return{run(t){T();let n=E();for(let e=re();e;e=re())t.push(e);return e.rawAt(n)}}}var Qn=new WeakMap;function $n(e){let t=Qn.get(e);return t||(t=N(e),Qn.set(e,t)),t}function er(e={}){let t={text:``,fresh:``},n=Tn(t),r=[n],i=(e,t,n)=>(r.includes(e)||r.push(e),Zn(e,t,n)),a=[],o=e.detect??[],s=Jn(o,e);if(s.length>0&&(P??=N(mn().forward),a.push(i(n,P,s))),o.includes(`injection`)){P??=N(mn().forward),fn??=N(mn().reversed);let e=Ln(t),r=Yn();a.push(i(n,fn,Xn()),i(An(n),P,r),i(e,P,r),i(An(e),P,r),i(En(n,et),P,r),i(En(n,e=>Ce(e)??e),P,r),i(zn(t),P,r))}if(o.includes(`marker_leak`)&&e.note){let t=Ot(e.note);a.push(i(n,yn(e.note),[{...Wn,id:0,regex:t}]))}if(o.includes(`tool_leak`)&&e.tools){let t=Ae(e.tools),r=t.map(({regex:e},t)=>({...Gn,id:t,regex:e}));t.length>0&&a.push(i(n,bn(t.map(({literal:e})=>e)),r))}for(let{detector:t,compiled:r,matchers:o}of e.own??[]){let e=o.map(({regex:e},n)=>({...R(t),id:n,regex:new RegExp(e.source,e.flags)}));a.push(i(n,$n(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 tr(e,t,n={},r=[]){let i=Ne(e,t).filter(e=>!(qe(e)||r.includes(e))),a=Ie(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=er({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=Oe(p,c,e,t,{detectors:o,scope:n});return m=m.filter(({start:e})=>e>=r+l.taken),l}}}function nr(e){let{context:t}=e,n=e.detect,r=n?tr(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(-pt),_=u,v=0,y=u,b=0,x=0,S=s?we(s):void 0;S?.push(u);function C(e){let n=[];if(S?.push(e)&&n.push([a,xt]),c){let r=_.length;_+=e;let i=Pe(_,r);_=_.slice(i),v+=i;let[a]=rt(_,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 ee(e){let t=l?C(e??``):[];return e&&r?.push(e),t.length===0?null:{hits:t,...n?{boundary:n.boundary}:{}}}function w(){let e=s&&a!==`flag`?E(s):h.length,n=c&&o!==`flag`?D(c,t.canary):h.length;return m+Math.min(e,n)}function T(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 E(e){let t=u.length+m,n=Math.max(t,x),r=Math.max(b,n-pt),i=r+jt(y.slice(r-b),e);i<n&&n>t&&(y=g+h,b=t-g.length,i=b+jt(y,e)),x=Math.min(i,u.length+p.length-pt);let a=Math.max(b,Math.max(t,x)-pt);return y=y.slice(a-b),b=a,Math.max(0,i-t)}function D(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+Ge(i,e,t)-u.length-m)}function O(e){let t=ee(e);if(t)return{blocked:!0,...t};let i=e===void 0,a=i?p.length:Math.min(w(),r?.holdFrom()??p.length),o=Math.max(0,a-m);if(!(n&&r))return T({blocked:!1,emit:te(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}:(te(s.taken),T({blocked:!1,emit:s.text??``,...s.action===`allow`?{}:{found:{action:s.action,hits:s.hits}}}))}function te(e){let t=h.slice(0,e);return h=h.slice(e),m+=t.length,l&&(g=(g+t).slice(-pt)),t}return{process(e){return e?(p+=e,h+=e,l&&(y+=e),O(e)):{blocked:!1,emit:``}},flush:()=>O(),accumulated:()=>p,unreleased:()=>h,drainUnreleased:()=>te(h.length),carryOut:()=>l?Te(u+p,s,c):``}}function z(e,t,n){return He(t,e.detect,n)}async function rr(e,t,n,r){return z(e,[n],t)?(await pn(),ir(e,t,n,r)):null}function ir(e,t,n,r){return z(e,[n],t)?nr({context:t,detect:{matrix:e.detect,boundary:n,rewrite:n===`reply`,scope:$e(e,t)},...r?{carry:r}:{}}):null}async function ar(e,t,n,r){return z(e,[n],r??t)?(await pn(),nr({context:t,detect:{matrix:e.detect,boundary:n,rewrite:!1,scope:r??$e(e,t)}})):null}var or=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}},sr=[`user`,`slots`,`repair`,`attachment`,`voice`,`history`,`system`];function cr(e,t){return e&&Object.fromEntries(Object.entries(e).map(([e,n])=>[e,t.read(n)]))}var lr={client:`untrusted`,server:`assembled`};function ur(e){return typeof e==`string`?e:JSON.stringify(e)}function dr(e,t){let n=[],r=!1;if(!e)return{context:e,events:n,blocked:r};let i={};for(let a of Dt){let o=e[a];if(o===void 0)continue;let s=t();i[a]=s.read(ur(o));let c=s.found(),l=Be(`context`,c);l&&n.push({...l,trust:lr[a]}),r||=c.action===`block`}return{context:i,events:n,blocked:r}}var fr=/^[A-Za-z0-9._-]+$/;function pr(e){let t=e?.trim();return t&&fr.test(t)?t:void 0}function mr(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 hr(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 gr(e,t){let n=t?`: ${t}`:``;return new j(`input`,`guardrails.detect blocked the request at ${e}${n}`,{copy:{key:`detect.blocked`}})}function _r(e,t){let{detect:n}=C(t.guardrails),r=ot(sr,e=>ht(e,n)),i=e.input??{},a=i.text===void 0?void 0:r.user.read(i.text),o=e.system===void 0?void 0:Bt(e.system,`TurnRequest.system`,e=>r.system.read(e)),s=cr(i.slots,r.slots),c=dr(i.context,()=>ht(`context`,n)),l=mr(i.repair,r.repair),u=i.history?hr(i.history,r.history):void 0,{attachments:d,voice:f}=i.attachments?.length||i.voice?.length?qt(t,i.attachments,i.voice,r):i,p=[],m;for(let e of sr){let t=r[e].found(),n=Be(e,t);n&&p.push(sn(n)),t.action===`block`&&(m??=gr(e,t.errorInternal))}return p.push(...c.events.map(sn)),c.blocked&&(m??=gr(`context`)),{request:{...e,system:o,projectId:pr(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}=_r(e,t);if(r)throw r;return n}function yr(e,t){return[...new Set([...t.filter(t=>ve(e,t)),...e.filter(e=>ve(t,e))])]}function br(e,t){let n=e.attachments?t?yr(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 xr(e){let t=O(e[0]??``);return t===`application/pdf`?`PDF`:t.split(`/`)[0]??t}function Sr(e,t){let n=Pt(e),r=Wt({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=>ve(t.accept,e.mimeType)).length>t.max&&r.push({code:`too_many_of_kind`,params:{maxFiles:t.max,kind:xr(t.accept)}})}let i=new Set;return r.filter(e=>{let t=JSON.stringify(e);return!i.has(t)&&(i.add(t),!0)})}var Cr=`final_answer`;function wr(e){return e.structured!==null&&e.tools.wire.length>0}function Tr(e,t,n){let{structured:r}=t;if(!r||!wr(t))return e;let i={type:`function`,name:Cr,description:M(`structured.answer_tool`,{},n),parameters:r.jsonSchema};return{...e,structured:null,wireTools:[...e.wireTools??[],i]}}function Er(e,t){return e.get(t)||{name:t,missing:!0}}function Dr(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 Or(e,t){return[...Ht(t),...Dr(t)].map(t=>Er(e,t))}function kr(e,t){if(Array.isArray(e)){for(let n of e)kr(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),kr(r,t);for(let e of Object.values(r))kr(e,t)}function Ar(e,t){let n=Or(e,t);if(n.length===0)return;let r=new Set;for(let e of n)`inputSchema`in e&&kr(e.inputSchema,r);return{names:n.map(({name:e})=>e),params:[...r]}}function jr(e){return!e||e.length===0?[]:e.slice(-4)}function Mr(e,t){if(e.length===0)return``;let n=e.map(e=>`${e.role===`user`?`User`:`Assistant`}: ${e.content}`);return`${M(`repair.history_heading`,{count:e.length},t)}\n${n.join(`
2
- `)}\n\n`}function Nr(e){let{profile:t,repair:n,history:r}=e,i=n.guidance||M(`repair.default_guidance`,{},t.labels),a=Mr(jr(r),t.labels),o=`${M(`repair.prompt_header`,{},t.labels)}\n\n`;return o+=`${M(`repair.prompt_intro`,{},t.labels)}\n\n`,o+=`${M(`repair.section_previous_output`,{},t.labels)}\n\`\`\`\n${n.previousOutput.trim()}\n\`\`\`\n\n`,o+=`${M(`repair.section_validator_rejection`,{},t.labels)}\n${n.rejection.trim()}\n\n`,i.trim()&&(o+=`${M(`repair.section_repair_guidance`,{},t.labels)}\n${i.trim()}\n\n`),a&&(o+=a),o+=`${M(`repair.section_instructions`,{},t.labels)}\n`,o+=M(`repair.prompt_instructions`,{},t.labels),o}function Pr(e,t){let n=[];return t&&n.push(`structured`),e.type===`image`&&n.push(`image`),e.type===`speech`&&n.push(`speech`),n}function Fr(e,t){let n=Pr(e,t);if(!(n.length<=1))throw new j(`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 Ir(e,t){if(e.type!==`speech`){if(t.speech)throw new j(`request`,`Profile ${e.id} (${e.type}) takes no speech settings — only a speech profile speaks`)}else if(t.system)throw new j(`config`,`Profile ${e.id} (speech) takes no system prompt — the input text is the transcript`)}function Lr(e,t){if(e.type===`transcription`){if(t.system)throw new j(`config`,`Profile ${e.id} (transcription) takes no system prompt — the input is the clip`);if(!t.input?.voice?.length)throw new j(`request`,`Profile ${e.id} (transcription) requires a voice clip`)}}function Rr(e,t){return e.type===`speech`?{...e.speech,...zr(t.speech)}:void 0}function zr(e){return Object.fromEntries(Object.entries(e??{}).filter(([,e])=>e!==void 0))}function Br(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 Vr(e){let t=se(e);if(!t)throw new j(`input`,`MIME '${e}' is not a supported media input type`);return t}function Hr(e){return e.map(e=>{let t=Vr(e.mimeType),n=O(e.mimeType),r=n===`image/jpg`?`image/jpeg`:n;return Ut(e)?{type:t,mimeType:r,uri:e.uri}:{type:t,mimeType:r,data:e.data}})}function Ur(e,t){let{text:n,repair:r,history:i}=t.input??{};if(e.type===`speech`&&!n?.trim())throw new j(`request`,`Profile ${e.id} (speech) requires text input`);if(k(e)?.text===!1&&n)throw new j(`request`,`Profile ${e.id} does not accept text input`);let a=r?Nr({profile:e,repair:r,history:i}):Gr(e,t)??n;if(e.type===`speech`)return a?{type:`text`,text:a}:null;let o=[...Wr(t),...a?[Ve(a)]:[]];return o.length>0?{type:`text`,text:o.join(`
3
-
4
- `)}:null}function Wr(e){let t=e.input?.context??{};return[...Dt].reverse().filter(e=>t[e]!==void 0).map(e=>ze(e,ur(t[e])))}function Gr(e,t){if(t.continueFrom&&re.includes(e.type)){if(t.input?.text)throw new j(`request`,`Profile ${e.id}: a continueFrom turn takes no input.text — its user message is the continue instruction`);return M(`continue.instruction`,{},e.labels)}}function Kr(e){return e.type===`image`&&e.image.references?Hr(e.image.references):[]}function qr(e,t){let n=t.input?.attachments??[],r=t.input?.voice??[];return[...Kr(e),...Hr(n),...Hr(r)]}function Jr(e,t){let n=[],r=Ur(e,t);return r&&n.push(r),n.push(...qr(e,t)),n}function Yr(e,t){let n=t.input?.slots;if(!n)return;let r=k(e)?.slots??{};for(let[t,i]of Object.entries(n)){let n=Object.hasOwn(r,t)?r[t]:void 0;if(!n)throw new j(`request`,`Profile ${e.id} has no slot '${t}'`);let a=Xt(n);if(!a.includes(i))throw new j(`request`,`Profile ${e.id}: slot '${t}' takes ${a.join(`, `)}, not '${i}'`)}}function Xr(e,t){let n=t.input?.context;if(!n)return;let r=k(e)?.context;for(let[t,i]of Object.entries(n))if(i!==void 0){if(!Dt.includes(t)||!r?.from.some(e=>e===t))throw new j(`request`,`Profile ${e.id} takes no context from '${t}'`);if(ur(i).length>r.maxChars)throw new j(`request`,`Profile ${e.id}: context from '${t}' is over inputs.context.maxChars (${String(r.maxChars)})`)}}var Zr=/\{([A-Za-z_][\w-]*)\}/g;function Qr(e,t,n,r){let i=k(e)?.slots;return i?t.replace(Zr,(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 j(`request`,`Profile ${e.id}: ${r} uses slot '${a}', and the request chose no value for it`);return o}):t}function $r(e,t,n){if(e.type===`speech`||e.type===`transcription`)return[];let r=e.identity.system;if(!r)return[];let i=Rt(e.id,e.identity.conditions,n,t);return Ft(r,i,n=>Qr(e,n,t,`identity.system`))}function ei(e,t){let n=$r(e,t.input?.slots,t);return{pieces:Lt([...n.map(({pieces:e})=>e),t.system===void 0?[]:Qt(t.system)]),lines:n.map(({line:e})=>e)}}function ti(e){return e.type!==`host`&&e.type!==`decision`&&e.type!==`embedding`}function ni(e,t){if(ti(e))return e;throw e.type===`host`?new j(`request`,`Profile ${e.id}: type 'host' never runs a model — ${t} is not supported; execute tools with invokeTool`):e.type===`embedding`?new j(`request`,`Profile ${e.id}: type 'embedding' runs through runEmbedding — ${t} is not supported`):new j(`request`,`Profile ${e.id}: type 'decision' runs through runDecision — ${t} is not supported`)}function ri(e,t){if(t){if(!e.allowModelSelect)throw new j(`request`,`Profile ${e.id} does not allow model selection`);if(!e.models[t])throw new j(`request`,`Unknown model '${t}' for ${e.id}`);return t}return e.defaultModel}function ii(e,t,n,r){let i=t.efforts;if(!i||Object.keys(i).length===0){if(r)throw new j(`request`,`Profile ${e.id} model '${n}' has no selectable efforts`);return}let a=Object.keys(i);if(r){if(!t.allowEffortSelect)throw new j(`request`,`Profile ${e.id} model '${n}' does not allow effort selection`);let a=i[r];if(!a)throw new j(`request`,`Unknown effort '${r}' for ${e.id} model '${n}'`);return a}return i[t.defaultEffort??a[0]]}function ai(e){if(e.summaries===!0)return`auto`;if(e.summaries===!1)return`none`}function oi(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 si(e){return e.type===`live`||e.outputs?.streaming?.mode!==`buffered`}function ci(e,t){return e.type===`live`?`live`:`turn`}function li(e,t){if(!t.continueFrom)return;if(e.type===`live`)throw new j(`request`,`Profile ${e.id}: type 'live' uses live.sessionResumption, not turnBehaviour.resumption/continueFrom`);let n=E(e)?.maxContinues;if(n===void 0)return;let r=t.continuation;if(r===void 0)throw new j(`request`,`Profile ${e.id}: continueFrom requires TurnRequest.continuation when turnBehaviour.resumption.maxContinues is set`);if(r<1)throw new j(`request`,`Profile ${e.id}: continuation must be >= 1`);if(r>n)throw new j(`request`,`Profile ${e.id}: continuation ${r} exceeds turnBehaviour.resumption.maxContinues (${n})`)}function ui(e,t){return z(C(t),[`live_reply`])?{...e,transcription:{...e?.transcription,output:!0}}:e}function di(e){let{detect:t}=C(e.guardrails);return e.type!==`speech`&&e.type!==`transcription`&&tt(t,`canary_leak`)?Ze():``}function fi(e,t,n,r){if(!r)return;let i={};for(let[a,o]of Object.entries(r)){if(!n.builtInTools?.includes(a))throw new j(`request`,`Profile ${e.id}: builtInArgs names '${a}', which model '${t}' does not list in builtInTools`);i[a]=o}return i}function pi(e,t,n){let r=ni(e.profiles.get(t.profile),`resolveTurn`);Yr(r,t),Xr(r,t);let i=vr(t,r),a=i.input??{};li(r,i);let o=n??ri(r,i.model),s=ye(r,o),c=tn(e.tools,r,i,o),l=c.builtins,u=oi(r,a.slots);if(Fr(r,u),u&&c.wire.some(e=>e.name===`final_answer`))throw new j(`config`,`Profile ${r.id}: a structured turn answers through '${Cr}', so no tool of its own may take that name`);Ir(r,i),Lr(r,i);let d=fi(r,o,s,i.builtInArgs),f=ci(r,s),p=e.providers.get(s.provider),m=p&&_e(p,s,r.type),h=ei(r,i);return{profile:r,generation:{model:o,apiId:s.apiId,transport:f,...m?{operationName:m}:{},stream:si(r),thinking:ii(r,s,o,i.effort),summaries:ai(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:Br(r),speech:Rr(r,i),live:r.type===`live`?ui(r.live,r.guardrails):void 0,input:Jr(r,i),canary:di(r),resolvedSystem:h.pieces,systemLines:h.lines,host:i.host}}}function mi(e){return e.type===`image`?e.image:null}function hi(e,t){let n=ni(t,`projectProfile`),{identity:r}=n,i=k(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:Or(e,n),inputs:i,outputs:a,image:mi(n),speech:n.type===`speech`?n.speech:null,live:n.type===`live`?n.live:null}}function gi(e,t){return hi(e.tools,e.profiles.get(t))}var _i=o({accepted:S,preparedInput:A});function B(e){return new j(`internal`,e)}function vi(e,t,n){return new j(e,t,{copy:{key:`tool.execution_uncertain`},cause:n})}function yi(e){return vi(`conflict`,`The tool operation is ${e}, so it does not run again until the host settles it`)}async function bi(e){let t=e=>Array.isArray(e)?e.map(t):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,n])=>[e,t(n)])):e,n=A.parse(t(Ei(e))),r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(n)));return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}var xi=T.tool.transform((e,t)=>e.tool.phase===`complete`||e.tool.phase===`error`?{...e,tool:e.tool}:(t.addIssue({code:`custom`}),g)),Si=o({finding:r(),data:A.optional(),parts:l(be).optional(),modelText:r().optional(),provenance:le.optional(),suspicious:l(ue).optional()}),Ci=T.tool.transform((e,t)=>e.tool.phase===`background`?{...e,tool:e.tool}:(t.addIssue({code:`custom`}),g)),wi=o({event:Ci,replay:o({modelResult:Si})}),Ti=o({event:xi,effects:c([`not_started`,`completed`,`unknown`]),replay:o({modelResult:Si.optional(),outputRaw:A.optional(),failure:o({code:r(),kind:fe,message:r(),error:r().optional(),details:A.optional()}).optional(),awaiting:h().optional(),denied:b(!0).optional(),callNotStarted:h().optional(),aborted:n([h(),o({reason:r().optional()})]).optional(),pendingInject:l(o({id:r().optional(),messages:l(pe),released:s().int().nonnegative().optional()})).optional()})});function Ei(e){let t=new Set,n=e=>{if(!e||typeof e!=`object`)return e;if(t.has(e))throw B(`Tool operation value has a cycle`);let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&r!==null)throw B(`Tool operation value holds an object that is not plain data`);if(Object.hasOwn(e,`__proto__`))throw B(`Tool operation value has an own __proto__ key`);t.add(e);try{if(Array.isArray(e))return e.map(n);let t=Object.entries(Object.getOwnPropertyDescriptors(e)),r=t.find(([,e])=>e.get||e.set);if(r)throw B(`Tool operation value has a getter or setter at '${r[0]}'`);return Object.fromEntries(t.filter(([,e])=>e.enumerable&&e.value!==void 0).map(([e,t])=>[e,n(t.value)]))}finally{t.delete(e)}};return A.parse(n(e))}var Di=`background`;function Oi(){return h().optional().describe(M(`tool.background_field`))}function ki(e,t){if(e?.background!==`ask`||typeof t!=`object`||!t)return{input:t,asked:!1};let{[Di]:n,...r}=t;return{input:r,asked:n===!0}}function Ai(e,t){let{background:n}=e;if(n!==void 0&&n!==`never`)return n===`always`?`claim`:n===`ask`?ki(e,t).asked?`claim`:void 0:n}function ji(e){let{tool:t,support:n,base:r,labels:i}=e;if(!t||!n)return;let a=Ai(t,e.input);if(a!==void 0)return{at:a,support:n,trace:n.openTrace(r.callId),reply:()=>{let e={finding:M(`tool.background_started`,{tool:t.name},i)},n=ce(e),a=de(r,{phase:`background`,readBack:n});return wi.parse(Ei({event:a,replay:{modelResult:e}}))}}}function Mi(e,t){if(e&&!t?.detach)throw new j(`config`,`A request with a background service needs a coordinator with detach`)}function Ni(e){let{name:t,background:n}=e;if(n!==void 0&&n!==`never`){if(e.answeredBy===`page`)throw new j(`config`,`Tool '${t}' sets background, which a tool answered by the page cannot`);if(typeof n==`object`&&!(Number.isFinite(n.afterMs)&&n.afterMs>=0))throw new j(`config`,`Tool '${t}' sets background.afterMs, which must be a time in milliseconds`)}}var Pi=/^[\x21-\x7E]{1,256}$/;function Fi(e=Date.now){let t=new Map,n=new Map,r=({tool:e,max:n})=>{if(n===void 0)return;let r=[...t.values()].filter(t=>t.tool===e).length;for(let[i,a]of t){if(r<=n)break;a.tool===e&&(t.delete(i),r--)}};return{get(n,i){let a=t.get(n);if(a&&(t.delete(n),!(i.idleMs!==void 0&&e()-a.usedAt>i.idleMs)))return t.set(n,{...a,usedAt:e(),tool:i.tool}),r(i),{id:a.id,protocolVersion:a.protocolVersion}},open(i,a,o){let s=n.get(i);if(s)return s;let c=o().then(n=>(t.delete(i),t.set(i,{...n,usedAt:e(),tool:a.tool}),r(a),n)).finally(()=>n.delete(i));return n.set(i,c),c},drop(e,n){t.get(e)?.id===n&&t.delete(e)},clear(){t.clear(),n.clear()}}}function Ii(e){return e!==null&&Pi.test(e)}async function Li(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(``)}var Ri=`after`;function zi(){return l(r()).optional().describe(M(`tool.after_field`))}function Bi(e,t,r,i){let a=t=>{if(t instanceof m){if(r in t.shape)throw new j(`config`,`Tool '${e}' sets ${r}, and its input already has a field of that name`);return t.safeExtend({[r]:i()})}if(t instanceof v){let e=t.options.map(a);return d(t.def.discriminator,e)}if(t instanceof _)return n(t.options.map(a));throw new j(`config`,`Tool '${e}' sets ${r}, which needs an object input or a union of objects`)};return a(t)}function Vi(e,t){return Bi(e,t,Ri,zi)}function Hi(e,t){if(!e.after||typeof t!=`object`||!t)return{input:t,names:[]};let{[Ri]:n,...r}=t;return{input:r,names:n??[]}}function Ui(e,t,n){return n?e.flatMap(e=>{let r=n.filter(n=>n.tool===e&&n.callId!==t).map(e=>e.callId);return r.length>0?r:[e]}):[]}var Wi=class{value;constructor(e){this.value=e}};function Gi(e){return new Wi(e)}function Ki(e){return(t,n)=>{let{page:r}=n;if(r&&`output`in r)return Gi(r.output);let{labels:i}=n.profile;throw r?.timedOut?Error(M(`tool.page_timed_out`,{},i)):Error(M(`tool.page_no_answer`,{tool:e},i))}}var qi=new WeakMap;function Ji(e,t){let n=qi.get(e);n||(n=new WeakMap,qi.set(e,n));let r=n.get(t);if(!r){let i=$t(e,`input`);Jt(i,`input`);let a=$t(t,`output`);Jt(a,`output`),r={inputSchema:i,outputSchema:a},n.set(t,r)}return r}function Yi(e){let{inputSchema:t,outputSchema:n}=Ji(e.input,e.output),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?te(n,r[t]):void 0;if(i)throw new j(`config`,`Tool "${e.name}" ${t} label: ${i}`)}return{inputSchema:structuredClone(t),outputSchema:structuredClone(n)}}function Xi(e,t){if(t&&(typeof t.service!=`string`||!t.service.trim()))throw new j(`config`,`Tool "${e}" signs in with slot "${t.slot}" but names no service`)}function Zi(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 j(`config`,`Tool "${e}" auth.queryParam ${r}`)}function Qi(e,t){if(t!==void 0&&!(Number.isInteger(t.requests)&&t.requests>0&&Number.isFinite(t.windowMs)&&t.windowMs>0))throw new j(`config`,`Tool "${e}" limit needs a whole number of requests above 0 and a window above 0 ms`)}function $i(e,t){if(!(t===void 0||Number.isFinite(t)&&t>0))throw new j(`config`,`Tool "${e}" timeoutMs needs a finite number of ms above 0`)}function V(e,t,n){if(!(n===void 0||Number.isInteger(n)&&n>0))throw new j(`config`,`Tool "${e}" ${t} needs a whole number above 0`)}function ea(e){V(e.name,`maxResponseBytes`,e.maxResponseBytes);let t=e.imageLimits;t&&(V(e.name,`imageLimits.count`,t.count),V(e.name,`imageLimits.bytes`,t.bytes),V(e.name,`imageLimits.totalBytes`,t.totalBytes),$i(e.name,t.timeoutMs))}function ta(e){return Zt(e.endpoint),Xi(e.name,e.auth),Zi(e.name,e.auth,e.mapping?.queryParams),Qi(e.name,e.limit),$i(e.name,e.timeoutMs),ea(e),{...e,type:`http`,...Yi(e)}}function na(e){return Xi(e.name,e.auth),Zi(e.name,e.auth),ea(e),V(e.name,`session.idleMs`,e.session?.idleMs),V(e.name,`session.max`,e.session?.max),{...e,type:`mcp`,...Yi(e)}}function ra(e){Xi(e.name,e.auth),Zi(e.name,e.auth);let t=e.answeredBy===`page`?Ki(e.name):e.handler;if(typeof t!=`function`)throw new j(`config`,`Tool '${e.name}' needs a handler, or answeredBy: 'page'`);return{...e,handler:t,type:`function`,...Yi(e)}}function ia(e){if(e.type===`builtin`||(Ni({name:e.name,...e.background===void 0?{}:{background:e.background},...e.type===`function`&&e.answeredBy?{answeredBy:e.answeredBy}:{}}),e.background!==`ask`))return e;let t=e.input,n=Bi(e.name,t,`background`,Oi);return{...e,askInputSchema:Ji(n,e.output).inputSchema}}function aa(e,t,n){return ia(oa(e,t,n))}function oa(e,t,n){if(e.type===`builtin`)return e;if(e.type===`agent`){let r=en(e,t,n),i=k(r),a=Yt({type:r.type,...i?{inputs:i}:{}},e),o=e.after?Vi(e.name,a):a,s=Yi({...e,input:o,output:Gt});return Kt(e,o,s)}let r=e.after?{...e,input:Vi(e.name,e.input)}:e;return r.type===`http`?ta(r):r.type===`mcp`?na(r):ra(r)}function sa(e=()=>void 0){let t=new Map,n=Fi(),r=e=>t.get(e),i=n=>{let i=aa(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 j(`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}}var ca=[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/wav`,`audio/mpeg`];function la(e){return e.join(`,`)}function ua(e){let t=e?.attachments?.accept,n=e?.voice?.accept;return{text:e?.text!==!1,attachments:t?.length?{accept:t,acceptAttr:la(t)}:null,voice:n?.length?{accept:n}:null,maxFiles:e?.maxFiles,maxBytes:e?.maxBytes,maxTurnBytes:e?.maxTurnBytes,limitsByMime:e?.limitsByMime,slots:Vt(e?.slots),context:e?.context}}function da(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 fa(e,t){let n=e=>(e??[]).map(({name:e,mimeType:t,sizeBytes:n})=>({name:e,mimeType:t,sizeBytes:n})),r=Wt({attachments:e.attachments?.accept,voice:e.voice?.accept,limits:Pt(da(e))},n(t.attachments),n(t.voice));return{ok:r.length===0,issues:r}}function pa(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(ca.filter(t=>ve(e,t)))??e.find(n):r(ca)}var ma=x({protocol:r(),provider:r(),apiId:r(),options:t(r(),u()).optional(),keySlot:r().optional(),fallbackKeySlot:r().optional(),efforts:t(r(),c(kt)).optional(),defaultEffort:r().optional(),allowEffortSelect:h().optional(),summaries:h().optional(),maxOutputTokens:s().optional(),temperature:s().optional(),builtInTools:l(r()).optional(),compaction:x({maxTokens:s(),compactAt:s(),previousExchanges:s(),profile:r().optional(),timing:c(ut),meter:c(Ke).optional()}).optional(),limits:x({operationTimeoutMs:s().optional(),connectTimeoutMs:s().optional(),liveStepTimeoutMs:s().optional(),maxWireRecordBytes:s().optional(),maxWireResponseBytes:s().optional(),maxEventBytes:s().optional(),maxStepBytes:s().optional(),maxStepEvents:s().optional(),maxPendingToolCalls:s().optional()}).optional()}),ha=x({structured:n([r(),x({by:r(),map:t(r(),r()),fallback:r()}),f()]).optional(),streaming:x({mode:c(it).optional(),streamThoughts:h().optional()}).optional()}),ga=x(ot(ft,()=>c(Mt))),_a=x(ot(Ue,()=>ga)),va=x({id:r(),label:r(),actions:ga,names:l(r()),find:h()}),ya=x({hosts:l(r()),fromTools:h()}),ba=x({quota:x({perDay:s()}).optional(),detect:_a,patterns:a(c(Ue),x({theorem:h(),names:l(r())})).optional(),host:l(va).optional(),allow:x({ungiven_images:ya,ungiven_links:ya}),blockedReply:x({onBlock:c(vt),maxRetries:s()})}),xa=n([h(),x({theorem:h(),host:h()})]),Sa=x({record:h(),writeTo:n([b(!1),r()]).optional(),sampleRate:s(),include:x({upstreamLog:h(),outboundWire:h(),evidenceRaw:h(),usage:h(),guardrailDecisions:h(),guardrailMatchPreview:h()}),scrub:x({sensitive:xa,injection:xa,canary:xa}),resource:an,retainForDays:s(),rotateAfterMiB:s(),hasOnWriteError:h()}),H=x({text:h(),attachments:x({accept:l(r()),acceptAttr:r()}).nullable(),voice:x({accept:l(r())}).nullable(),maxFiles:s().optional(),maxBytes:s().optional(),maxTurnBytes:s().optional(),limitsByMime:t(r(),s()).optional(),slots:t(r(),x({label:r().optional(),choices:l(x({value:r(),description:r().optional()}))})).optional(),context:x({from:l(c(Dt)),maxChars:s()}).optional()}),Ca=x({allowContinue:l(c(bt)).optional(),autoContinue:l(c(bt)).optional(),maxContinues:s().optional()}),wa=x({resumption:Ca.optional()}),Ta=x({allow:l(r()),page:l(r()),t2Loader:r().optional(),parallel:h().optional()}),U={providerContinuation:x({history:c([`host`,`stateless`,`provider`]).optional()}).optional(),id:r(),models:t(r(),ma),defaultModel:r(),allowModelSelect:h().optional(),maxSteps:s().optional(),labels:a(c(We),r()),guardrails:ba.optional(),observability:Sa.optional()},Ea=n([r(),o({private:r().min(1)})]),Da=n([r(),l(n([r(),l(Ea).readonly()])).min(1).readonly()]),Oa=x({handle:r(),conditions:t(r(),l(r()).readonly()).readonly().optional(),system:Da.optional()}),W=d(`type`,[x({...U,type:b(`text`),identity:Oa,outputs:ha.optional(),inputs:H,tools:Ta,turnBehaviour:x({resumption:Ca.optional(),allowSteering:h().optional(),atStepLimit:c(dt).optional()}).optional(),canStop:b(!0),allowSteering:h()}),x({...U,type:b(`image`),identity:Oa,outputs:ha.optional(),image:x({aspectRatio:r().optional(),resolution:r().optional(),mimeType:r().optional(),quality:r().optional(),background:r().optional(),n:s().int().min(1).optional(),seed:s().int().optional(),outputCompression:s().int().min(0).max(100).optional(),references:l(n([x({mimeType:r(),data:r(),name:r().optional()}),x({mimeType:r(),uri:r(),name:r().optional()})])).optional(),includeText:h().optional()}),inputs:H,tools:Ta,turnBehaviour:wa.optional(),canStop:b(!0)}),x({...U,type:b(`transcription`),identity:x({handle:r()}),maxSteps:y().optional(),outputs:ha.optional(),inputs:H,canStop:b(!0)}),x({...U,type:b(`speech`),identity:x({handle:r()}),outputs:ha.optional(),speech:x({voice:r().optional(),style:r().optional(),speed:s().optional(),format:c(yt).optional()}),inputs:H,turnBehaviour:wa.optional(),canStop:b(!0)}),x({...U,type:b(`live`),identity:Oa,inputs:H.pick({slots:!0,context:!0}).optional(),live:x({ingress:x({audio:h().optional(),video:h().optional(),text:h().optional()}).optional(),voice:r().optional(),vad:x({activityHandling:c(Et).optional(),startSensitivity:c(_t).optional(),endSensitivity:c(st).optional(),prefixPaddingMs:s().optional(),silenceDurationMs:s().optional()}).optional(),sessionResumption:h().optional(),contextCompression:x({triggerTokens:s().optional(),slidingWindow:x({targetTokens:s().optional()})}).optional(),transcription:x({input:h().optional(),output:h().optional()}).optional()}),tools:Ta.pick({allow:!0,page:!0}),turnBehaviour:x({allowSteering:h().optional()}).optional()})]);function ka(e){let t=C(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:Aa(t.allow.ungiven_images),ungiven_links:Aa(t.allow.ungiven_links)},blockedReply:t.blockedReply}}function Aa(e){return{hosts:[...e.hosts??[]],fromTools:e.fromTools??!0}}function ja(e){return e===void 0||e===!1||typeof e==`string`?e:`custom`}function Ma(e){if(!e)return;let t=nn(e);return{record:t.record,writeTo:ja(t.writeTo),sampleRate:t.sampleRate,include:t.include,scrub:t.scrub,resource:t.resource,retainForDays:t.retainForDays,rotateAfterMiB:t.rotateAfterMiB,hasOnWriteError:!!t.onWriteError}}function Na(e){let{greeting:t,resumed:n,...r}=e??{};return r}function Pa(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=zt(t),r=It(t);return{allow:[...Ht(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 Fa({allow:e,page:t}){return{allow:e,page:t}}function Ia(e,t){let n=ua(e.inputs),r=t?.identity??{handle:e.handle},i=t?ka(t.guardrails):void 0,a=t?Ma(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:ke(t?.labels)};switch(e.type){case`text`:return W.parse({...s,type:`text`,inputs:n,tools:Pa(e,t),turnBehaviour:t?.type===`text`?t.turnBehaviour:void 0,canStop:!0,allowSteering:!t||oe(t)});case`image`:return W.parse({...s,type:`image`,image:e.image??{},inputs:n,tools:Pa(e,t),turnBehaviour:t?.type===`image`?t.turnBehaviour:void 0,canStop:!0});case`speech`:return W.parse({...s,type:`speech`,speech:e.speech??{},inputs:n,turnBehaviour:t?.type===`speech`?t.turnBehaviour:void 0,canStop:!0});case`transcription`:return W.parse({...s,type:`transcription`,inputs:n,canStop:!0});case`live`:return W.parse({...s,type:`live`,live:Na(e.live),...e.inputs?{inputs:{slots:n.slots,context:n.context}}:{},tools:Fa(Pa(e,t))});default:return e.type}}function La(e,t){let n=ni(e,`interfaceFromProfile`);return Ia(hi(t,n),n)}function Ra(e){return p(t=>w.safeParse(e(t)).success)}var za=[`running`,`gate`,`background`,`complete`,`error`,`cancel`],Ba=p(e=>{let t=w.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 za.some(e=>e===n)}),Va=t(r(),i()),Ha=x({operationId:r().optional(),name:r(),callId:r(),arguments:Va,draft:r().optional(),reasoning:l(ee).optional(),stepId:r().optional(),edited:x({from:Va,to:Va}).optional(),activity:r().optional(),activityPast:r().optional(),outputDraft:r().optional(),state:Ba.optional(),startedAt:s().optional(),endedAt:s().optional(),artifacts:l(i()),get steps(){return l(Ha).optional()}}),Ua=x({kind:c(Ee),native:r().optional()}),G={id:r()},K=d(`kind`,[x({...G,kind:b(`user-text`),text:r()}),x({...G,kind:c([`user-attachment`,`user-voice`]),name:r(),mimeType:r(),sizeBytes:s(),data:r().optional()}),x({...G,kind:b(`thought`),text:r()}),x({...G,kind:b(`text`),text:r()}),x({...G,kind:b(`tool`),tool:Ha}),x({...G,kind:b(`structured`),value:i(),draft:r().optional()}),x({...G,kind:b(`media`),mimeType:r(),data:r().optional(),url:r().optional(),previewUrl:r().optional()}),x({...G,kind:b(`grounding`),grounding:Ra(e=>({type:`grounding`,grounding:e}))}),x({...G,kind:b(`citation`),sources:Ra(e=>({type:`citation`,sources:e})),callId:r().optional()}),x({...G,kind:b(`evidence`),evidence:Ra(e=>({type:`evidence`,evidence:e}))}),x({...G,kind:b(`guardrail`),guardrail:me}),x({...G,kind:b(`error`),message:r()}),x({...G,kind:b(`turn-done`),stop:Ua.optional(),tokens:Ra(e=>({type:`tokens`,tokens:e})).optional(),interactionId:r().optional(),compaction:h().optional(),workedMs:s().optional(),endedAt:s().optional()})]),Wa=x({type:r()});function Ga(e,t){return Object.hasOwn(e,t)}function Ka(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=>Ka(e,n)).join(` | `)}]`}).join(`; `)}function qa(e){return Ka(e.issues,[])}function Ja(e,t){return new j(`bad_response`,`${e} failed its wire check: ${qa(t)}`)}function q(e,t,n){let r=e.safeParse(t);if(!r.success)throw Ja(n,r.error);return r.data}function Ya(e){return{type:`malformed`,error:new j(`bad_response`,e,{copy:{key:`session.part_skipped`}})}}function Xa(e,t){let n=Wa.safeParse(t);if(!n.success)return Ya(`a line without a kind failed its wire check: ${qa(n.error)}`);let{type:r}=n.data;if(!Ga(e,r))return{type:`unsupported`,received:r,raw:t};let i=e[r].safeParse(t);return i.success?i.data:Ya(`a '${r}' line failed its wire check: ${qa(i.error)}`)}function Za(e){try{return{value:JSON.parse(e)}}catch(e){if(e instanceof SyntaxError)return;throw e}}function Qa(e,t){let n=Za(t);return n?Xa(e,n.value):Ya(`a line is not JSON`)}function $a(e){let t=Za(e);if(!t)throw new j(`bad_response`,`a line is not JSON`);return t.value}var eo=x({name:r(),mimeType:r(),data:r()}),to=x({slots:t(r(),r()).optional(),context:i().optional(),text:r().optional(),attachments:l(eo).optional(),voice:l(eo).optional()}),no=x({gateKind:c(At).optional(),sessionPermissions:l(r()).optional(),name:r().optional(),input:i().optional(),snapshot:ae.optional(),promoted:l(r()).optional(),model:r().optional(),effort:r().optional()}),J=r().trim().min(1),ro=x({path:r().optional(),conditions:t(r(),r()).optional()}),io=ro;x({input:to,conversation:r().min(1).optional(),model:r().optional(),effort:r().optional(),stated:ro.optional(),turnId:J.optional(),abandon:l(D).min(1).optional(),replay:no.pick({sessionPermissions:!0}).optional(),transcript:l(K).optional()});var ao=[`approve`,`deny`],oo=n([o({unanswered:b(!0)}),o({output:i()}).refine(e=>`output`in e).transform(e=>({output:e.output}))]);x({gateId:r().min(1),operationId:r().min(1).max(256),decision:c(ao),input:i().optional(),secret:r().optional(),page:oo.optional(),conversation:r().min(1).optional(),turnId:J.optional(),replay:no.optional()}),x({turnId:J,id:J,inject:l(pe).min(1)}),x({turnId:J});var so=x({type:b(`conversation`),ref:r().min(1),posted:b(!0).optional()}),co={...T,conversation:so},lo=x({transcript:l(K),paused:x({events:l(w),blocks:l(K)}).optional()});x({conversation:r().min(1)}),x({conversation:r().min(1),at:s().int().min(-1)}),x({blocks:l(K)});var uo=x({conversation:r().min(1),view:lo}),fo=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 po(e){return e instanceof fo}function mo(e){return e?.trim()||void 0}var ho=x({error:r().optional(),errorKind:fe.optional(),errorCopy:ge.optional(),errorInternal:r().optional()}),go=ho;function _o(e,t){let n=mo(e.error),r=mo(e.errorInternal);return new fo(e.errorKind??t,n,r&&r!==n?r:void 0,e.errorCopy)}function vo(e){return!po(e)||e.copy===void 0?!1:(Array.isArray(e.copy)?e.copy:[e.copy]).some(e=>e.key===`session.conversation_unknown`)}function yo(e,t){let n=Qa(e,t);if(n.type===`error`)throw _o(ho.parse(n),`internal`);return n}function bo(e,t,n){let r=e.split(`
5
- `),i=r.pop()??``;for(let e of r)e.trim()&&n(yo(t,e));return i}async function xo(e,t,n,r){if(!e.body)throw new j(`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(;;){Se(r);let{done:e,value:s}=await i.read();if(e)break;o=bo(o+a.decode(s,{stream:!0}),t,n)}let e=o.trim();e&&n(yo(t,e))}finally{r?.removeEventListener(`abort`,s)}}async function So(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 Co(e,t){let n=await e.text(),r;try{r=JSON.parse(n),t?.(r)}catch{return _o({errorInternal:`HTTP ${String(e.status)}`},De(e.status))}let i=ho.safeParse(r);return i.success?_o({...i.data,errorInternal:i.data.errorInternal??`HTTP ${String(e.status)}`},De(e.status)):new j(`bad_response`,`HTTP ${String(e.status)} error body failed its wire check`)}async function wo(e,t,n){let r=n.fetch??globalThis.fetch.bind(globalThis);try{return await r(e,{...t,headers:await So(n),credentials:n.credentials??`same-origin`})}catch(e){throw Xe(e)?e:new j(`network`,Ye(e),{cause:e})}}async function To(e,t,n,r,i={}){await xo(await Eo(e,t,i),n,r,i.signal)}async function Eo(e,t,n){let r=await wo(e,{method:`POST`,body:JSON.stringify(t),signal:n.signal},n);if(!r.ok)throw await Co(r);return r}async function Do(e,t,n={}){await Eo(e,t,n)}async function Y(e,t,n={}){let r=await wo(e,{...t.body===void 0?{method:`GET`}:{method:`POST`,body:JSON.stringify(t.body)},signal:t.signal},n);if(!r.ok)throw await Co(r,t.failed);return $a(await r.text())}async function Oo(e,t,n={}){let{signal:r,...i}=n;return q(lo,await Y(e,{body:t,signal:r},i),`the conversation`)}async function ko(e,t,n,r){let{signal:i,...a}=n;return q(uo,await Y(e,{body:t,signal:i},a),r)}function Ao(e,t,n={}){return ko(e,t,n,`the rewound conversation`)}function jo(e,t,n={}){return ko(e,t,n,`the started conversation`)}function Mo(e){let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)}var No=x({interface:W});function Po(e={}){let t=Mo(e.endpoint??`/api/theorem`);return{async describe(n){let r=await wo(t,{method:`GET`,signal:n},e);if(!r.ok)throw await Co(r);return q(No,$a(await r.text()),`the profile description`).interface},turn:({replay:n,...r},i,a)=>To(`${t}/turn`,r,co,i,{...e,signal:a}),invoke:({replay:n,...r},i,a)=>To(`${t}/invoke`,r,co,i,{...e,signal:a}),conversation:(n,r)=>Oo(`${t}/conversation`,n,{...e,signal:r}),rewind:(n,r)=>Ao(`${t}/rewind`,n,{...e,signal:r}),pageResult:(n,r)=>Do(`${t}/page-result`,n,{...e,signal:r}),steer:n=>Do(`${t}/steer`,n,e),stop:n=>Do(`${t}/stop`,n,e)}}function Fo(e,t){if(typeof e==`string`)return e;let n=Array.isArray(e)?e:Object.keys(e);return n.length?Fo(n[0],t):t}function Io(e){return Object.entries(e).map(([e,t])=>({id:e,type:t.type,labels:t.type===`choice`?Object.keys(t.criteria):t.type===`score`?t.criteria.map((e,t)=>Fo(e,String(t))):[],...t.type===`box`&&t.image!==void 0?{image:t.image}:{}}))}function Lo(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:Io(t),...n&&Object.keys(n).length>0?{images:n}:{},...e.observability?{observability:{record:nn(e.observability).record}}:{}}}function Ro(e,t){let n=Object.keys(t??{}).find(t=>e&&Object.hasOwn(e,t));if(n!==void 0)throw new j(`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 X=s().min(0).max(1),zo=t(r(),X),Bo=d(`type`,[x({type:b(`choice`),choice:r(),confidence:X,probabilities:zo}),x({type:b(`noul`),noul:X}),x({type:b(`box`),box:x({top:X,bottom:X,left:X,right:X}),confidence:X}),x({type:b(`score`),score:s().nonnegative(),confidence:X,legend:t(r(),r().min(1)),probabilities:zo})]),Vo=x({id:r(),type:c([`choice`,`noul`,`score`,`box`]),labels:l(r()),image:r().optional()}),Ho=x({result:x({model:r().min(1),questions:l(Vo).optional(),answers:t(r(),Bo),usage:x({inputTokens:s().int().nonnegative(),outputTokens:s().int().nonnegative(),costUsd:s().nonnegative().optional()}).optional()}),traces:l(rn).optional()}),Uo=new WeakMap;function Wo(e,t){return t.length>0&&typeof e==`object`&&e&&Uo.set(e,t),e}function Go(e){return typeof e==`object`&&!!e&&Uo.get(e)||[]}var Ko=x({traces:l(rn)});async function qo(e,t,n,r,i){let a=[],o=e=>{let t=Ko.safeParse(e);t.success&&(a=t.data.traces)};try{return i(await Y(e,{body:t,signal:n,failed:o},r))}catch(e){throw Wo(e,a)}}function Jo(e,t,n,r={}){return qo(e,t,n,r,Yo)}function Yo(e){return q(Ho,e,`the decision`)}var Xo=x({interface:x({type:b(`decision`),identity:x({handle:r()}),contract:r(),maxStateBytes:s().optional(),questions:l(Vo),build:x({input:t(r(),i()).optional()}).optional(),images:t(r(),x({mimeType:c([`image/png`,`image/jpeg`]),data:r()})).optional(),observability:x({record:h()}).optional()})});function Zo(e={}){let t=(e.endpoint??`/api/decision`).replace(/\/$/,``);return{async describe(n){return q(Xo,await Y(t,{signal:n},e),`the decision description`).interface},decide:(n,r,i,a)=>Jo(`${t}/decide`,{state:n,...i?{assets:i}:{},...a===void 0?{}:{input:a}},r,e)}}function Qo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n.trim():void 0}function Q(e,t){if(!URL.canParse(t))return;let n=new URL(t);if(n.protocol===`http:`||n.protocol===`https:`)return{title:e.trim()||n.hostname.replace(/^www\./,``),uri:n.href,type:`web`}}function $o(e){let t=new Set;return e.filter(e=>!t.has(e.uri)&&(t.add(e.uri),!0))}function es(e){let t=[...e.matchAll(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g)].flatMap(e=>Q(e[1]??``,e[2]??``)??[]),n=[...e.matchAll(/https?:\/\/[^\s"'<>\]]+/g)].flatMap(e=>{let t=(e[0]??``).replace(/[),.;:]+$/,``);return Q(t,t)??[]});return $o([...t,...n])}function ts(e){if(Array.isArray(e))return e;if(!Qo(e))return[];for(let t of[`items`,`results`,`search_results`,`models`,`datasets`]){let n=e[t];if(Array.isArray(n))return n}return[]}function ns(e,t){return $o(e.flatMap(e=>Qo(e)?t(e)??[]:[]))}function rs(e,t){let n=t===`dataset`?`https://huggingface.co/datasets/`:`https://huggingface.co/`;return ns(ts(e),e=>{let t=Z(e,`id`)??Z(e,`modelId`);return t?Q(t,`${n}${t}`):void 0})}function is(e){return ns(ts(e),e=>{let t=Z(e,`html_url`),n=Z(e,`full_name`)??Z(e,`name`);return t?Q(n??t,t):void 0})}function as(e){return e.replace(/<[^>]+>/g,``).replace(/\s+/g,` `).trim()}function os(e){if(typeof e!=`string`)return es(JSON.stringify(e));let t=[...e.matchAll(/<entry\b[\s\S]*?<\/entry>/g)];return t.length===0?es(e):$o(t.flatMap(e=>{let t=/<id>(https?:\/\/[^<]+)<\/id>/.exec(e[0]??``)?.[1],n=/<title>([\s\S]*?)<\/title>/.exec(e[0]??``)?.[1];return t?Q(as(n??t),t)??[]:[]}))}function $(e){if(typeof e==`string`)return es(e);if(Array.isArray(e)||Qo(e)){let t=ns(ts(e),e=>{let t=Z(e,`html_url`)??Z(e,`url`)??Z(e,`source_url`)??Z(e,`contentUrl`),n=Z(e,`title`)??Z(e,`name`)??t;return t?Q(n??t,t):void 0});return t.length>0?t:es(JSON.stringify(e))}return[]}var ss={search_models:e=>rs(e,`model`),search_datasets:e=>rs(e,`dataset`),search_github:is,list_arxiv:os,search_web:$,read_pages:$,read_model_card:$,read_dataset_card:$,read_readme:$,find_library:$,read_library_docs:$,ask_repo_docs:$};function cs(e){return ss[e]}function ls(e,t){let n=cs(e);return n?{...t,sources:n}:t}function us(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}:{},...t.after?{after:!0}:{},...t.background?{background:t.background}:{}};if(t.type===`agent`){e.register({...r,type:`agent`,profile:t.profile,...t.maxCallsPerTurn===void 0?{}:{maxCallsPerTurn:t.maxCallsPerTurn}});return}let i={...r,input:he(t.inputSchema),output:he(t.outputSchema)};if(t.type===`http`){e.register(ls(t.name,{...i,type:`http`,endpoint:t.endpoint,method:t.method,headers:t.headers,mapping:t.mapping,auth:t.auth,maxResponseBytes:t.maxResponseBytes}));return}if(t.type===`mcp`){e.register(ls(t.name,{...i,type:`mcp`,serverUrl:t.serverUrl,mcpToolName:t.mcpToolName,headers:t.headers,auth:t.auth,maxResponseBytes:t.maxResponseBytes,session:t.session}));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??on(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 ds(e,t,n){e.registerMany([...ne,...ie]);for(let r of t)us(e,r,n)}function fs(e,t,n,r,i){if(ds(e.tools,n,i),r&&t.type!==`live`)for(let{id:t,spec:n}of[r,...r.also??[]])e.schemas.register(t,n);return e.profiles.register(t),t}function ps(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 ms(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 hs(e){if(e.type!==`compaction`||e.failure?.errorInternal===void 0)return e;let{errorInternal:t,...n}=e.failure;return{...e,failure:n}}function gs(e){if(e.type!==`guardrail`||!(e.guardrail?.errorInternal||e.guardrail?.errorSummary))return e;let{errorInternal:t,errorSummary:n,...r}=e.guardrail;return{...e,guardrail:r}}function _s(e){if(e.type!==`evidence`||!e.evidence?.raw)return e;let{raw:t,...n}=e.evidence;return{...e,evidence:n}}function vs(e,t){let n=t?.reader===`builder`?ps(e):hs(gs(ms(e)));return t?.includeEvidenceRaw||(n=_s(n)),n=ln(n,!1),n}function ys(e,t){return e.map(e=>vs(e,t))}function bs(e,t,n){let{error:r=``,errorKind:i,errorCopy:a}=vs(Re(gt(e),t),n);return{error:r,errorKind:i,...a?{errorCopy:a}:{}}}var xs={reader:`builder`};function Ss(e){return e.mode===`demo`?{reader:`visitor`}:xs}export{wi as $,qa as A,Ui as B,go as C,tr as Ct,To as D,sn as Dt,Do as E,cn as Et,pa as F,ji as G,Ii as H,fa as I,B as J,ki as K,sa as L,Xa as M,K as N,io as O,ln as Ot,La as P,Ti as Q,Wi as R,_o as S,z as St,vo as T,pn as Tt,Li as U,Fi as V,Mi as W,_i as X,Ei as Y,bi as Z,Po as _,_r as _t,ys as a,Xr as at,Ao as b,rr as bt,Zo as c,Cr as ct,Go as d,Sr as dt,vi as et,Jo as f,br as ft,fo as g,vr as gt,co as h,hr as ht,vs as i,Qr as it,Qa as j,q as k,Ro as l,wr as lt,Wo as m,dr as mt,Ss as n,gi as nt,fs as o,Jr as ot,qo as p,gr as pt,yi as q,bs as r,pi as rt,ds as s,Ar as st,xs as t,ri as tt,Lo as u,Tr as ut,Oo as v,or as vt,po as w,er as wt,jo as x,ir as xt,Y as y,ar as yt,Hi as z};
@@ -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{c as o,i as s,l as c}from"./SegmentedControlItem-CZs-ycSA.js";import{t as l}from"./VStack-CkVMcNiK.js";import{n as u,t as d}from"./StackItem-CQviqAfM.js";import{S as f,h as p,s as m,t as h,v as g}from"./browser-transport-DKhZ4zo1.js";import{t as _}from"./mergeProps-ptS-gIMz.js";import{l as v}from"./fieldParts-CoOpDoax.js";import{t as y}from"./Icon-BqkS-pIq.js";import{a as b,c as x,l as S,p as C,u as w}from"./SidePanel-DEd3R1Q3.js";import{t as T}from"./Text-BOqCfzZC.js";import{a as E,n as D,t as O}from"./labels-provider-uONlWExD.js";import{a as ee,c as k,n as A,t as j}from"./IconButton-DVUFx-8p.js";import{t as M}from"./Dialog-Sd04KQS2.js";import{t as N}from"./createReactComponent-CZwsv6DD.js";import{a as P,i as F,t as I}from"./Banner-CrhjYjDy.js";import{n as L,t as R}from"./Center-CgO0c-qo.js";import{_ as z,g as te,h as ne,m as re,n as ie,r as ae,t as oe}from"./studio-labels-q6eBFSru.js";import{c as B}from"./host-patterns-F-KZIzkF.js";import{Lr as se,Sr as V,er as ce,tr as le}from"./shaped-data-7q5Be8sp.js";import{S as ue,g as de,r as fe,t as pe}from"./reader-747-Cvu8.js";import{i as H}from"./live-ingress-OuSlQ6q7.js";import{i as me,y as he}from"./turn-client-OLK12Fyi.js";import{r as ge,t as _e}from"./live-messages-M0vS3YB0.js";import"./use-second-ticker-D6JSf9B3.js";import{t as ve}from"./EmptyState-C_uF9Wyj.js";import{Et as ye,Ft as be,H as xe,J as Se,T as Ce,Tt as we,X as Te,_t as Ee,c as De,g as Oe,i as U,p as ke,wt as Ae}from"./index-CAK9cdCh.js";var je=N(`outline`,`camera-rotate`,`CameraRotate`,[[`path`,{d:`M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2`,key:`svg-0`}],[`path`,{d:`M11.245 15.904a3 3 0 0 0 3.755 -2.904m-2.25 -2.905a3 3 0 0 0 -3.75 2.905`,key:`svg-1`}],[`path`,{d:`M14 13h2v2`,key:`svg-2`}],[`path`,{d:`M10 13h-2v-2`,key:`svg-3`}]]),Me=N(`outline`,`microphone-off`,`MicrophoneOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1`,key:`svg-1`}],[`path`,{d:`M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85`,key:`svg-2`}],[`path`,{d:`M8 21l8 0`,key:`svg-3`}],[`path`,{d:`M12 17l0 4`,key:`svg-4`}]]),Ne=N(`outline`,`phone-off`,`PhoneOff`,[[`path`,{d:`M3 21l18 -18`,key:`svg-0`}],[`path`,{d:`M5.831 14.161a15.946 15.946 0 0 1 -2.831 -8.161a2 2 0 0 1 2 -2h4l2 5l-2.5 1.5c.108 .22 .223 .435 .345 .645m1.751 2.277c.843 .84 1.822 1.544 2.904 2.078l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a15.963 15.963 0 0 1 -10.344 -4.657`,key:`svg-1`}]]),Pe=N(`outline`,`phone`,`Phone`,[[`path`,{d:`M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2`,key:`svg-0`}]]),Fe=N(`outline`,`subtitles`,`Subtitles`,[[`path`,{d:`M18 5a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3l12 0`,key:`svg-0`}],[`path`,{d:`M7 15h5`,key:`svg-1`}],[`path`,{d:`M15 15h2`,key:`svg-2`}],[`path`,{d:`M17 12h-3`,key:`svg-3`}],[`path`,{d:`M11 12h-1`,key:`svg-4`}]]),Ie=N(`outline`,`video-off`,`VideoOff`,[[`path`,{d:`M3 3l18 18`,key:`svg-0`}],[`path`,{d:`M15 11v-1l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -.675 .946`,key:`svg-1`}],[`path`,{d:`M10 6h3a2 2 0 0 1 2 2v3m0 4v1a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2v-8a2 2 0 0 1 2 -2h1`,key:`svg-2`}]]),Le=N(`outline`,`video`,`Video`,[[`path`,{d:`M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4`,key:`svg-0`}],[`path`,{d:`M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8`,key:`svg-1`}]]);function Re(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 ze(e){return!(e.isMuted||!e.socketOpen||e.modelPlaying&&e.rms<e.bargeInRmsWhileSpeaking)}function Be(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 Ve(e,t){if(e.phase===void 0){t.toolCalls.push({id:e.callId,name:e.name,arguments:e.arguments,...e.operationId?{operationId:e.operationId}:{}});return}if(e.phase===`cancel`){t.cancelledToolIds.add(e.callId);return}if(e.phase!==`error`)return;let n=t.toolCalls.findIndex(t=>t.id===e.callId);n!==-1&&t.toolCalls.splice(n,1)}var He=new Set;async function Ue(e){let{executeToolOnRelay:t,name:n,toolArgs:r,callId:i,operationId:a}=e,o=e.pageTools&&Object.hasOwn(e.pageTools,n)?e.pageTools[n]:void 0,s=await t({callId:i,operationId:a}),c=new Set;for(;s.status!==`settled`;){if(s.status===`dispatched`){if(c.has(s.grantId))return;c.add(s.grantId);let e=s.grantId,r=s.arguments;!o&&!He.has(n)&&(He.add(n),console.warn(`Theorem: page tool '${n}' has no handler in pageTools; the agent gets no answer.`));let l=o?await Promise.resolve().then(()=>o(r,{callId:i,operationId:a})).catch(()=>void 0):void 0;s=await t({callId:i,operationId:a,grantId:e,...l?{output:l.output}:{unanswered:!0}});continue}let{gate:l}=s,u=l.kind===`page`||!e.onGate?{decision:`deny`}:await e.onGate({callId:i,toolName:n,input:l.preparedArguments??r,gate:l});if(u===`withdrawn`)return;if(u.decision===`deny`){await t({callId:i,operationId:a,decision:`deny`});return}s=await t({callId:i,decision:`approve`,operationId:a,...u.secret===void 0?{}:{secret:u.secret}})}}function We(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 Ge=`mic-capture-processor`;function Ke(){return new URL(`data:text/javascript;base64,LyoqCiAqIEF1ZGlvV29ya2xldCBwcm9jZXNzb3IgdGhhdCBmb3J3YXJkcyBtb25vIG1pYyBmcmFtZXMgdG8gdGhlIG1haW4gdGhyZWFkLgogKiBQbGFpbiBKUzogaXQgcnVucyBpbiB0aGUgQXVkaW9Xb3JrbGV0R2xvYmFsU2NvcGUgYXMgaXRzIG93biBtb2R1bGUsIGxvYWRlZAogKiBieSBVUkwgKHNlZSBgLi4vbWljLWNhcHR1cmUudHNgKSwgc28gaXQgaW1wb3J0cyBub3RoaW5nIGFuZCBzaGlwcyBhcyBpcy4KICovCnJlZ2lzdGVyUHJvY2Vzc29yKAogICdtaWMtY2FwdHVyZS1wcm9jZXNzb3InLAogIGNsYXNzIE1pY0NhcHR1cmVQcm9jZXNzb3IgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogICAgcHJvY2VzcyhpbnB1dHMpIHsKICAgICAgY29uc3QgY2hhbm5lbCA9IGlucHV0c1swXVswXTsKICAgICAgY29uc3QgY29weSA9IG5ldyBGbG9hdDMyQXJyYXkoY2hhbm5lbCk7CiAgICAgIHRoaXMucG9ydC5wb3N0TWVzc2FnZShjb3B5LCBbY29weS5idWZmZXJdKTsKICAgICAgcmV0dXJuIHRydWU7CiAgICB9CiAgfSwKKTsK`,``+import.meta.url)}function qe(e,t,n=16e3){if(t===n)return Je(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 Je(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 Ye(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 Xe(){return{toolCalls:[],mediaChunks:[],cancelledToolIds:new Set}}var Ze=.05,Qe=[500,1e3,2e3,4e3,8e3];function K(e){return e instanceof Error?e:new B(`internal`,V(e),{cause:e})}function q(e){if(e&&typeof e.disconnect==`function`)try{e.disconnect()}catch{}}function $e(e){if(e&&typeof e.getTracks==`function`)for(let t of e.getTracks())t.stop()}function et(e){let t=Ae(e.inputFloat32),n=e.hasPlaybackNodes||e.status===`speaking`;return ze({isMuted:e.isMuted,socketOpen:e.wsOpen,modelPlaying:n,rms:t,bargeInRmsWhileSpeaking:Ze})}function tt(e,t){return e===`listening`&&t?`working`:e===`working`&&!t?`listening`:null}var nt=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 B(`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,stated:t,openMessage:n}=this.options;return{type:`open`,...this.history.length?{history:structuredClone(this.history)}:{},...e?{slots:e}:{},...t?{stated:t}:{},...this.context===void 0?{}:{context:this.context},...this.providerState?{resume:{providerState:this.providerState,awayMs:this.droppedAt===void 0?0:Date.now()-this.droppedAt}}:{},...n?{host:n}:{}}}handleDrop(){!this.providerState||this.sessionOver?(this.teardownConnection(),this.setStatus(`disconnected`)):(this.droppedAt??=Date.now(),this.teardownConnection(),this.setStatus(`reconnecting`),this.scheduleReconnect())}scheduleReconnect(){let e=Qe[this.reconnectTries];if(e===void 0){let e=this.droppedAt;this.failSession(new B(`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 B(`timeout`,`live connect timed out`))},2e4),this.ws.onmessage=e=>{this.enqueueServerMessage(e.data)},this.ws.onclose=()=>{this.opening?this.failOpen(new B(`network`,`live socket closed before ready`)):this.handleDrop()},this.ws.onerror=()=>{!this.opening&&this.providerState&&!this.sessionOver?this.handleDrop():this.failOpen(new B(`network`,`live socket error`))}}catch(e){this.failOpen(new B(`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=We(e);this.failSession(new B(t?`auth`:`internal`,V(e),{cause:e,copy:{key:t?`voice.permission`:`voice.unavailable`}}))}finally{this.micActivating=!1}}}sendMicFrame(e,t){let n=qe(e,t,16e3),r=le(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?.(we(e),!0)}forwardMicBuffer(e){if(this.reportMicVolume(e),et({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(Ke()),!0),this.micWorklet=new AudioWorkletNode(this.audioContext,Ge),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?.(ye(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(()=>Ue({executeToolOnRelay:e=>this.executeToolOnRelay(e),pageTools:this.options.pageTools,onGate:this.options.onGate,name:e.name,toolArgs: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=Xe();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`:Ve(e.tool,t);break;case`done`:this.handleDoneTurnEvent(e)}}handleEvidenceTurnEvent(e){let t=Be(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=tt(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 B(`request`,`live session is not connected`);let n=_e.safeParse({...e,type:`executeTool`});if(!n.success||n.data.type!==`executeTool`)throw new B(`request`,se(`error.request`));let r=n.data;if(this.pendingExecuteResults.has(r.operationId))throw new B(`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=ce(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=Ye(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.takeUpAgain())}setStated(e){JSON.stringify(e)!==JSON.stringify(this.options.stated)&&(this.options={...this.options,stated:e},this.takeUpAgain())}takeUpAgain(){this.providerState&&!this.opening&&this.ws?.readyState===WebSocket.OPEN&&this.handleDrop()}setContext(e){this.context=e,this.flushContext()}flushContext(){if(this.opening||this.ws?.readyState!==WebSocket.OPEN)return;let e=JSON.stringify(this.context);e!==this.sentContext&&(this.sentContext=e,this.ws.send(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,$e(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 rt(){return{turns:[],interimUser:``,interimAgent:``,working:!1}}function it(e,t){return t.length===0?e:[...e,[...t]]}function at(e,t){return e?t?t.startsWith(e)||e.startsWith(t)?t.length>=e.length?t:e:ot(e,t):e:t}function ot(e,t){return e?t?!e.endsWith(` `)&&!t.startsWith(` `)&&!/^\s/.test(t)&&!/^[\s.,!?;:]/.test(t)?`${e} ${t}`:`${e}${t}`:e:t}function st(e){return`${String(Date.now())}-${String(e.turns.length)}`}function ct(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:ot(s.text,t)};else{let n=i?.forceNew?t:at(c,t);o.push({id:st(e),role:a,text:n})}return{...e,turns:o,interimUser:n?``:e.interimUser,interimAgent:n?e.interimAgent:``}}function lt(e){return e.type===`thought`||e.type===`tool`||e.type===`citation`}function ut(e,t){return e.findIndex(e=>e.role===`work`&&e.events.some(e=>e.type===`tool`&&e.tool.callId===t))}function dt(e,t){if(t.type===`tool`&&t.tool.phase!==void 0)return t.tool.phase===`gate`?-1:ut(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 ft(e,t){if(t.type===`done`)return e.working?{...e,working:!1}:e;if(!lt(t))return e;let n=dt(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:st(e),role:`work`,events:[t]},{...e,turns:r,working:!0}}function pt(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 mt=24;function ht(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n}function gt(e,t){let n=e.trim();return ht(n,t.trim())>=Math.min(n.length,mt)}function _t(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`&&gt(t.text,e.text))})}function vt(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=>_t(e).flatMap(pt)).filter(e=>e.length>0);return{blocks:a.flat(),callStarts:a.slice(1).map(e=>e[0].id)}}function yt({working:e,interimAgent:t}){return t!==``||e}function bt(e){return!e.interimUser&&!e.interimAgent?e:{...e,interimUser:``,interimAgent:``}}function xt(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 St=.62,Ct=400;function wt(e){return navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:e},width:{ideal:640},height:{ideal:480}},audio:!1})}function Tt(e,t){let n=t?.facingMode??`user`;return wt(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 B(`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`,St).split(`,`)[1];t&&e(t)};return r.play().then(()=>{o||s||(o=setInterval(l,Ct))}),{video:r,facingMode:()=>c.facing,flip:async()=>{if(s)return c.facing;let e=c.facing===`user`?`environment`:`user`,t=await wt(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 Et(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=>ct(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 Tt(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 Dt(e){return new de(e.kind,e.error,e.message)}function Y(e){e.gateCallId===void 0&&e.clearActiveTool()}function Ot(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(Dt(e.failure)),Y(t)):t.setActiveTool(e.name)}function kt(e,t){e.type===`done`?(t.clearInterim(),Y(t)):e.type===`tool`&&Ot(e.tool,t)}function At(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)(rt),[_,v]=(0,J.useState)(null),[y,b]=(0,J.useState)(null),[x,S]=(0,J.useState)(``),[C,w]=(0,J.useState)(!1),[T,E]=(0,J.useState)([]),[D,O]=(0,J.useState)(!1),[ee,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)(T),I=(0,J.useRef)(t);return N.current=h,P.current=c,F.current=T,I.current=t,(0,J.useEffect)(()=>{C&&O(!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:w,sessionPermissions:T,setSessionPermissions:E,everConnected:D,videoPreview:ee,setVideoPreview:k,videoFacingMode:A,setVideoFacingMode:j,videoCaptureRef:M,captionsRef:N,isMutedRef:P,sessionPermissionsRef:F,statusRef:I,resetCaptions:(0,J.useCallback)(()=>{g(rt())},[]),stopVideo:(0,J.useCallback)(()=>{M.current&&=(M.current.stop(),null),k(null),j(`user`),d(!1)},[])}}function jt(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=>ft(e,t)),kt(t,{gateCallId:r.current?.callId,withdrawGate:()=>{o(`withdrawn`)},clearInterim:()=>{e.setCaptions(e=>bt(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 B(`cancelled`,`live session ended with a gate open`)),i.current=null,a.current=null,n(null)},[])}}function Mt(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 Nt(e,t,n,r){r.setCaptions(r=>ct(r,e,t,n?.interim))}async function Pt(e,t){let n=await t.waitForGateDecision(e);if(n===`withdrawn`)return`withdrawn`;let r=z({toolName:e.toolName,gate:e.gate,sessionPermissions:t.sessionPermissionsRef.current,resolution:n});return r.decision===`approve`&&(t.sessionPermissionsRef.current=r.sessionPermissions,t.setSessionPermissions(r.sessionPermissions)),r}function Ft(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 nt({...e,slots:r.slots,stated:r.stated,context:r.context,voiceIngress:r.voiceAvailable,onConnectPhase:e=>{r.setConnectPhase(e)},onStatusChange:e=>{Mt(e,n.current)},onTranscript:(e,t,r)=>{Nt(e,t,r,n.current)},onTurnEvent:e=>{e.type!==`unsupported`&&(e.type===`malformed`?n.current.reportFailure(e.error):(e.type===`tool`&&e.tool.phase===void 0&&n.current.clearFailure(),n.current.handleLiveTurnEvent(e)))},onTrace:e=>{n.current.traces.push(e)},onVolumeLevel:(e,t)=>{let r=n.current;t?r.setInputLevel(r.isMutedRef.current?0:e):r.setOutputLevel(e)},onError:e=>{n.current.reportFailure(e)},onSessionEnded:e=>{n.current.reportSessionEnded(e)},get pageTools(){return n.current.pageTools},onGate:e=>Pt(e,n.current)});return t.current=i,i},[]),clearClient:(0,J.useCallback)(()=>{t.current&&=(t.current.disconnect(),null)},[])}}function It(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=>it(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 Lt(e,t,n={}){let r=At(e.labels),i=jt({setCaptions:r.setCaptions,setActiveTool:r.setActiveTool,reportFailure:r.reportFailure}),a=(0,J.useRef)(t);a.current=t;let o=H(e.live.ingress,`audio`),s=H(e.live.ingress,`video`),c=H(e.live.ingress,`text`),l=(0,J.useMemo)(()=>Re({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)(g,[]),{clientRef:d,ensureClient:f,clearClient:p}=Ft({slots:n.slots,stated:n.stated,context:n.context,pageTools:n.pageTools,voiceAvailable:o,traces:u,handleLiveTurnEvent:i.handleLiveTurnEvent,waitForGateDecision:i.waitForGateDecision,gatePromptRef:i.gatePromptRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,videoCaptureRef:r.videoCaptureRef,setConnectPhase:r.setConnectPhase,setStatus:r.setStatus,setSessionActive:r.setSessionActive,reportFailure:r.reportFailure,clearFailure:r.clearFailure,reportSessionEnded:r.reportSessionEnded,clearSessionEnded:r.clearSessionEnded,setCaptions:r.setCaptions,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setActiveTool:r.setActiveTool,setSessionPermissions:r.setSessionPermissions,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),m=Et({clientRef:d,videoCaptureRef:r.videoCaptureRef,connectionRef:a,statusRef:r.statusRef,isMutedRef:r.isMutedRef,sessionPermissionsRef:r.sessionPermissionsRef,ensureClient:f,clearClient:p,cancelGateDecision:i.cancelGateDecision,stopVideo:r.stopVideo,resetCaptions:r.resetCaptions,sessionActive:r.sessionActive,textAvailable:c,videoAvailable:s,voiceAvailable:o,isVideoOn:r.isVideoOn,textDraft:r.textDraft,setTextDraft:r.setTextDraft,setCaptions:r.setCaptions,reportFailure:r.reportFailure,clearFailure:r.clearFailure,setIsMuted:r.setIsMuted,setSessionActive:r.setSessionActive,setSessionPermissions:r.setSessionPermissions,setStatus:r.setStatus,setConnectPhase:r.setConnectPhase,setInputLevel:r.setInputLevel,setOutputLevel:r.setOutputLevel,setVideoPreview:r.setVideoPreview,setVideoFacingMode:r.setVideoFacingMode,setIsVideoOn:r.setIsVideoOn}),{callStarted:h,ended:_,pastCalls:v,startCall:y,handleEnd:b,handleRestart:x}=It(m,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);(0,J.useEffect)(()=>{d.current?.setSlots(C===void 0?void 0:JSON.parse(C))},[d,C]);let w=JSON.stringify(n.stated);return(0,J.useEffect)(()=>{d.current?.setStated(w===void 0?void 0:JSON.parse(w))},[d,w]),xt(e.tools.page,n.pageTools),{handle:e.identity.handle,traces:u,callStarted:h,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:m.handleSendText,handleToggleMic:m.handleToggleMic,handleFlipCamera:m.handleFlipCamera,handleToggleVideo:m.handleToggleVideo,resolveGateDecision:i.resolveGateDecision}}var X=t(),Rt={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}},zt={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}]},Bt={sm:2,md:2,lg:2},Vt={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 Ht({startContent:e,centerContent:t,endContent:i,label:o,size:c=`md`,gap:l=1,orientation:u=`horizontal`,variant:d=`transparent`,dividers:f,xstyle:p,className:m,style:h,ref:g,onKeyDown:y,onFocus:b,onBlur:x,role:S,"aria-label":C,"aria-orientation":w,...T}){let E=t!=null,D=e!=null,O=i!=null,A=f?.includes(`bottom`)??!1,j=a[Rt[l]],{listRef:M,handleKeyDown:N,handleFocus:P}=v({itemSelector:`button, input, [tabindex]`,boundarySelector:`[role="toolbar"], [popover]`,orientation:u,hasRovingTabIndex:!0,hasCaretGuard:!0}),{hintElement:F,onKeyDown:I,onFocus:L,onBlur:R}=s({orientation:u}),z=(0,J.useCallback)(e=>{y?.(e),!e.defaultPrevented&&(I(e),N(e))},[y,I,N]),te=(0,J.useCallback)(e=>{b?.(e),!e.defaultPrevented&&(L(e),P(e))},[b,L,P]),ne=(0,J.useCallback)(e=>{x?.(e),!e.defaultPrevented&&R(e)},[x,R]);return(0,X.jsx)(ee,{value:c,children:(0,X.jsx)(Se,{ref:g,variant:d,paddingBlock:Bt[c],dividers:f,xstyle:p,className:m,style:h,children:(0,X.jsxs)(`div`,{ref:M,role:`toolbar`,"aria-label":o,"aria-orientation":u,onKeyDown:z,onFocus:te,onBlur:ne,..._(r(`toolbar`,{size:c}),n(E?Z.baseGrid:Z.baseFlex,u===`vertical`&&Z.vertical,zt.base,Q.gap(j),A&&Q.tabIndicatorBottom(`calc(-1 * (${Vt[c]} + 1px))`))),...T,children:[E?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(`div`,{...n(Z.startSlot,k.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,k.inset($[c]),Q.gap(j)),children:i})]}):(0,X.jsxs)(X.Fragment,{children:[D&&(0,X.jsx)(`div`,{...n(Z.startSlot,!O&&Z.startOnly,k.inset($[c]),Q.gap(j)),children:e}),O&&(0,X.jsx)(`div`,{...n(Z.endSlot,!D&&Z.endOnly,k.inset($[c]),Q.gap(j)),children:i})]}),F]})})})}Ht.displayName=`Toolbar`;function Ut(e){return(0,X.jsx)(O,{children:(0,X.jsx)(Wt,{...e})})}function Wt({handle:e,captions:t,pastCalls:n,draftText:r,onDraftTextChange:i,onSubmit:a,isDisabled:o,showComposer:s=!0,leading:c}){let u=D(),f=u(`@theorem.agent.handle`,{handle:e}),{blocks:p,callStarts:m}=vt(n,t),h=u(`@theorem.live.new_session`),g=Object.fromEntries(m.map(e=>[e,h])),_=s?(0,X.jsx)(xe,{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)(b,{label:u(`@theorem.panel.captions.name`),children:(0,X.jsx)(Ce,{blocks:p,dividers:g,handle:f,streaming:yt(t)})}):(0,X.jsx)(l,{height:`100%`,vAlign:`center`,padding:4,children:(0,X.jsx)(ve,{icon:(0,X.jsx)(y,{icon:Fe,size:`lg`,color:`secondary`}),title:u(`@theorem.panel.captions.empty.title`),description:u(`@theorem.panel.captions.empty.description`),isCompact:!0})})}),_]})}var Gt=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 B(`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 h(),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 B(`auth`,`Fill the vault slot this model names.`);let[c]=this.queued.splice(0,1);if(typeof c!=`string`)throw new B(`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 Kt(e,t){let n,r=t.execution?void 0:e=>n??=e.browserExecution();return{createSocket:()=>new Gt(e,t,r)}}var qt=720,Jt=320;function Yt({theme:e,mode:t,labels:n,...r}){return(0,X.jsx)(m,{theme:e,mode:t,children:(0,X.jsx)(O,{labels:n,children:(0,X.jsx)(Xt,{...r})})})}function Xt({iface:e,connection:t,trace:n,slots:r,stated:i,context:a,pageTools:s}){let u=D(),d=Lt(e,t,{slots:r,stated:i,context:a,pageTools:s}),f=(0,J.useRef)(null),p=P(e,d.traces,n),m=C(f,!0),h={name:u(`@theorem.panel.captions.name`),show:u(`@theorem.panel.captions.show`),hide:u(`@theorem.panel.captions.hide`),resize:u(`@theorem.panel.captions.resize`)},g=(0,X.jsx)(w,{labels:h,icon:(0,X.jsx)(y,{icon:be}),panelId:m.id,open:m.open,onToggle:m.toggle});return d.callStarted?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(F,{inspector:p,children:(0,X.jsx)(c,{ref:f,height:`fill`,header:(0,X.jsx)(S,{children:p.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(c,{height:`fill`,end:(0,X.jsx)(x,{id:m.id,labels:h,resizable:m.resizable,open:m.open,children:(0,X.jsx)(tn,{model:d})}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(l,{height:`100%`,padding:3,children:(0,X.jsx)(Qt,{model:d,captionsToggle:g})})})})})})}),(0,X.jsx)(sn,{prompt:d.gatePrompt,agent:u(`@theorem.agent.handle`,{handle:d.handle}),onResolve:d.resolveGateDecision})]}):(0,X.jsx)(F,{inspector:p,children:(0,X.jsx)(c,{ref:f,height:`fill`,header:(0,X.jsx)(S,{children:p.toggle}),content:(0,X.jsx)(o,{padding:0,children:(0,X.jsx)(Zt,{model:d})})})})}function Zt({model:e}){let t=D();return(0,X.jsx)(l,{minHeight:`100%`,vAlign:`center`,gap:8,paddingInline:3,children:(0,X.jsx)(R,{axis:`horizontal`,width:`100%`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:Oe,gap:8,children:[(0,X.jsxs)(l,{gap:1,children:[(0,X.jsx)(T,{type:`large`,as:`h2`,children:t(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{type:`display-2`,as:`h1`,children:t(`@theorem.live.greeting`)})]}),(0,X.jsxs)(u,{gap:2,wrap:`wrap`,children:[(0,X.jsx)(A,{label:t(e.voiceAvailable?`@theorem.live.start_voice_call`:`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(y,{icon:Pe}),onClick:()=>e.startCall({video:!1})}),e.videoAvailable?(0,X.jsx)(A,{label:t(`@theorem.live.start_video_call`),variant:`secondary`,icon:(0,X.jsx)(y,{icon:Le}),onClick:()=>e.startCall({video:!0})}):null]})]})})})}function Qt({model:e,captionsToggle:t}){let n=D(),r=$t();return(0,X.jsx)(l,{ref:r,height:`100%`,hAlign:`center`,children:(0,X.jsxs)(l,{width:`100%`,maxWidth:qt,height:`100%`,gap:3,children:[(0,X.jsxs)(l,{gap:.5,children:[(0,X.jsx)(T,{type:`label`,color:`secondary`,children:n(`@theorem.agent.handle`,{handle:e.handle})}),(0,X.jsx)(T,{size:`sm`,color:`secondary`,children:E(n,e.liveState,e.activeTool)})]}),e.failure?(0,X.jsx)(I,{status:`error`,role:`alert`,title:e.failure.error}):null,e.sessionEnded?(0,X.jsx)(I,{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:Jt,style:{color:`var(--color-icon-primary)`},"aria-hidden":`true`,children:(0,X.jsx)(Te,{status:e.status,levelsRef:e.levelsRef,toolActive:e.toolActive,variant:`hero`})})})}),(0,X.jsx)(en,{model:e,captionsToggle:t})]})})}function $t(){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 en({model:e,captionsToggle:t}){let n=D(),r=!e.sessionActive,i=[];return e.voiceAvailable&&i.push((0,X.jsx)(U,{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)(y,{icon:L}),pressedIcon:(0,X.jsx)(y,{icon:Me}),onPressedChange:e.handleToggleMic},`mic`)),e.videoAvailable&&(i.push((0,X.jsx)(U,{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)(y,{icon:Le}),pressedIcon:(0,X.jsx)(y,{icon:Ie}),onPressedChange:()=>{e.handleToggleVideo()}},`video`)),e.isVideoOn&&i.push((0,X.jsx)(j,{label:n(`@theorem.live.flip_camera`),tooltip:n(`@theorem.live.flip_camera`),variant:`ghost`,isDisabled:r,icon:(0,X.jsx)(y,{icon:je}),onClick:()=>{e.handleFlipCamera()}},`flip`))),i.push((0,X.jsx)(J.Fragment,{children:t},`captions`),e.canRestart?(0,X.jsx)(j,{label:n(`@theorem.live.start_call`),tooltip:n(`@theorem.live.start_call`),variant:`primary`,icon:(0,X.jsx)(y,{icon:Pe}),onClick:()=>{e.handleRestart()}},`call`):(0,X.jsx)(j,{label:n(`@theorem.live.end_call`),tooltip:n(`@theorem.live.end_call`),variant:`destructive`,isDisabled:r,icon:(0,X.jsx)(y,{icon:Ne}),onClick:e.handleEnd},`call`)),(0,X.jsx)(Ht,{label:n(`@theorem.live.controls`),dividers:[`top`],centerContent:(0,X.jsx)(u,{gap:2,vAlign:`center`,children:i})})}function tn({model:e}){return(0,X.jsx)(Ut,{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)(nn,{video:e.videoPreview,facingMode:e.videoFacingMode}):null})}function nn({video:e,facingMode:t}){let n=D(),r=(0,J.useRef)(null);return(0,J.useEffect)(()=>{let t=r.current;if(t)return Object.assign(e.style,{width:`100%`,height:`100%`,objectFit:`cover`,display:`block`}),t.replaceChildren(e),()=>{e.parentElement===t&&t.removeChild(e)}},[e]),(0,J.useEffect)(()=>{e.style.transform=t===`user`?`scaleX(-1)`:``},[e,t]),(0,X.jsx)(re,{ratio:4/3,fit:`cover`,children:(0,X.jsx)(`div`,{ref:r,"aria-label":n(`@theorem.live.camera_preview`),role:`img`})})}var rn=4,an=432,on={background:`transparent`,boxShadow:`none`};function sn({prompt:e,agent:t,onResolve:n}){return(0,X.jsx)(M,{isOpen:e!==null,purpose:`required`,width:an,padding:rn,style:on,onOpenChange:e=>{e||n({action:`deny`})},children:e?e.gate.kind===`auth`?(0,X.jsx)(ae,{gate:e.gate,toolName:e.gate.tool,onAuthenticated:e=>{n({action:`auth`,secret:e})}}):(0,X.jsx)(ie,{gate:e.gate,toolName:e.gate.tool,agent:t,input:e.input,onDecision:e=>{n({action:e})}}):null})}function cn({runtime:e,...t}){let{payload:n}=t;return(0,X.jsx)(un,{...t,connect:()=>e?Kt(n,e):ne(n)})}function ln({endpoint:e,...t}){let{actingAs:n}=De();return(0,X.jsx)(un,{...t,connect:()=>({createSocket:()=>new WebSocket(ke(e,n))})})}function un({payload:e,note:t,connect:n,trace:r,slots:i,stated:a,context:o}){let s=(0,J.useMemo)(()=>p(e),[e]),c=(0,J.useMemo)(()=>te(e),[e]);return s.type===`live`?(0,X.jsx)(Yt,{labels:oe,iface:s,connection:()=>(t(),n()),trace:r,slots:i,stated:a,context:o,pageTools:c}):null}export{ln as ProjectLive,cn as StudioLive};
@@ -1,3 +0,0 @@
1
- import{C as e,Cn as t,M as n,Wt as r,Xt as i,h as a,j as o,n as s,p as c,t as l,vn as ee,y as te,z as u}from"./tool-schema-6RWBAqGO.js";import{An as d,Cn as ne,Hn as re,Nn as f,Pn as ie,Sn as ae,Wn as oe,an as se,br as p,gr as m,pn as h,yn as g}from"./shaped-data-7q5Be8sp.js";import{a as _,r as v}from"./live-ingress-OuSlQ6q7.js";var ce=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],le={identity:d,inputs:f(`inputs`).filter(e=>e!==`decision`)},y=ce.map(e=>({...e,profileTypes:le[e.id]??f(e.profilePath)}));function ue(e){return y.find(t=>t.id===e)}function de(e){return e.modelBindings.length>1}function fe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function b(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function pe(e,t){let n=new Set(e.modelBindings.filter(n=>{let r=b(e,n);return r.keySlot===t||r.fallbackKeySlot===t}).map(e=>e.provider));return e.providers.filter(e=>n.has(e.id))}function me(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function he(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var ge=h,x=[{name:`operationTimeoutMs`,label:`Call timeout`,units:`ms`,isTimer:!0},{name:`connectTimeoutMs`,label:`Connect timeout`,units:`ms`,isTimer:!0},{name:`liveStepTimeoutMs`,label:`Live step timeout`,units:`ms`,isTimer:!0},{name:`maxWireRecordBytes`,label:`Wire record`,units:`bytes`,isTimer:!1},{name:`maxWireResponseBytes`,label:`Wire response`,units:`bytes`,isTimer:!1},{name:`maxEventBytes`,label:`Event`,units:`bytes`,isTimer:!1},{name:`maxStepBytes`,label:`Step`,units:`bytes`,isTimer:!1},{name:`maxStepEvents`,label:`Step events`,units:`events`,isTimer:!1},{name:`maxPendingToolCalls`,label:`Tool calls`,units:`calls`,isTimer:!1}],S=2147483647,C={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},w={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function T(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function E(e){return{key:T(`model`),modelId:`fast`,protocol:`openRouterOpenAi`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var D=`Studio stub tool — returns a fixed result.`;function O(e){return{key:T(`tool`),toolName:`my_tool`,toolType:`function`,description:D,category:`studio`,access:g[0],permission:ne[0],loadTier:ae[0],paths:[`*`],inputJson:l,outputJson:s,...e}}function k(e,t,n){return(!e.description.trim()||e.description===D)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function A(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function j(){return{key:``,label:``,at:p(m,()=>`ignore`),patterns:[A()],hint:``}}function M(){let e=t(void 0);return{canaryBindNote:``,detect:p(ie,t=>({...e.detect[t]})),sources:Object.fromEntries(re.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function N(){let e=_({});return{writeTo:c,destination:c,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:e.scrub.sensitive,injection:e.scrub.injection,canary:e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function P(e){return e.map(([e,t])=>({key:T(`criterion`),label:e,text:t}))}function F(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:T(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:P([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:T(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:P([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var I=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),L=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),_e=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
2
-
3
- `),ve=`How do I delete every screenshot on my desktop?`;function ye(e,t=`choice`){let n=q(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:T(`question`),id:n,type:t,instructions:``,criteria:B(t)}}function be(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=q(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:T(`image`),name:i,...n}}function xe(e){let t=q(`slot`,e.map(e=>e.name),e=>`slot_${String(e)}`);return{key:T(`slot`),name:t,label:``,choices:[R(),R()]}}function Se(){return{key:T(`condition`),name:``,values:[]}}function R(){return{key:T(`choice`),value:``,description:``}}function z(){return{key:T(`criterion`),label:``,text:``}}function B(e){return e===`noul`||e===`box`?[]:P(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function Ce(){return{identity:{agentId:``,profileType:``,handle:``,system:``,conditions:[]},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...e],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMime:{},slots:[],contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:i({type:`text`}),atStepLimit:`stop`},guardrails:M(),observability:N(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:v(`audio`),ingressVideo:v(`video`),ingressText:v(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:F(),labels:{}}}var we=new Set([`guardrails`]);function V(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&we.has(e.id))}function H(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return y.filter(e=>e.role!==`branch`&&V(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function U(e,t){let n=e.identity.profileType;return n!==``&&f(t).includes(n)}function Te(e){return U(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function Ee(e){let t=e.identity.profileType;return t!==``&&r.includes(t)}function W(e){let t=e.identity.profileType;return t?y.filter(n=>n.role===`spine`&&n.optional&&V(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function De(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>ee(se,e)),voiceAccept:[]}}function Oe(e){return{...e,text:!1,attachmentsAccept:[],voiceAccept:e.voiceAccept.length?e.voiceAccept:[`audio/*`]}}function ke(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function G(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ae(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:G(e.models.defaultModel,n)},modelBindings:n}}function K(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=te(r,t),o=q(a.modelId,i,e=>`${a.modelId}${e}`);return E({...a,modelId:o})}function je(e){return O({toolName:q(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function q(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Me(e,t,n){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let r=e.modelBindings.filter(r=>{let i=o(e.providers,t,r),a=e.providers.find(e=>e.id===r.provider);return u(a,t,r.protocol)&&!Fe(n,t,i)}),i={...e,identity:{...e.identity,profileType:t},modelBindings:r},s=r.length?r:[K(i,n?.start)],c=!e.models.key&&fe({...i,modelBindings:s}),l=t===`speech`&&!e.speech.voice.trim()&&s.some(n=>a(o(e.providers,t,n)));return{...i,inputs:t===`image`?De(e.inputs):t===`transcription`?Oe(e.inputs):e.inputs,...l?{speech:{...e.speech,voice:Ne}}:{},models:{...e.models,defaultModel:G(e.models.defaultModel,s),key:c?Ie:e.models.key},modelBindings:s}}var Ne=`Kore`,Pe=[`text`,`image`,`speech`,`transcription`,`live`,`decision`];function Fe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&Pe.some(e=>e!==t&&r(e))}var Ie=`slot_a`;function Le(e,t){return W(e).includes(t)?{...e,included:[...e.included,t]}:e}function Re(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function J(e){return`modelBinding:${e}`}var Y=`toolSpec:`;function X(e){return`${Y}${e}`}function Z(e){return e.startsWith(Y)?e.slice(9):void 0}var Q=`provider:`;function ze(e){return`${Q}${e}`}function Be(e){return e.startsWith(Q)?e.slice(9):void 0}var Ve=new Map(y.map(e=>[e.id,e.label]));function He(e){return Ve.get(e)??e}function Ue(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=Z(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=H(e);if(r===void 0&&a.includes(t))return{facet:t}}function We(e,t){return t===`models`?e.modelBindings.map(e=>({id:J(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||`Unnamed model`,children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:X(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||`Unnamed tool`,children:[]}))}function Ge(e){let t=H(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:He(t),children:We(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||`Unnamed agent`,children:t}}export{B as A,Te as B,H as C,W as D,q as E,j as F,b as G,Me as H,A as I,he as J,me as K,xe as L,be as M,ye as N,Le as O,K as P,R,U as S,Re as T,Ee as U,Ae as V,ke as W,y as X,pe as Y,ue as Z,S as _,Ge as a,E as b,$ as c,ve as d,_e as f,ge as g,x as h,Ue as i,z as j,Se as k,C as l,w as m,Be as n,Z as o,L as p,de as q,ze as r,X as s,J as t,I as u,k as v,T as w,O as x,Ce as y,je as z};